gpt4 book ai didi

java - 在 Java 中构建 SQL 字符串的最简洁方法

转载 作者:IT老高 更新时间:2023-10-28 11:30:01 24 4
gpt4 key购买 nike

我想构建一个 SQL 字符串来进行数据库操作(更新、删除、插入、选择等)——而不是使用数百万个“+”和引号的糟糕的字符串 concat 方法,在最好的——必须有更好的方法。

我确实考虑过使用 MessageFormat - 但它应该用于用户消息,虽然我认为它会做一个合理的工作 - 但我想应该有一些更符合 java sql 库中的 SQL 类型操作的东西。

Groovy 有用吗?

最佳答案

首先考虑在准备好的语句中使用查询参数:

PreparedStatement stm = c.prepareStatement("UPDATE user_table SET name=? WHERE id=?");
stm.setString(1, "the name");
stm.setInt(2, 345);
stm.executeUpdate();

可以做的另一件事是将所有查询保存在属性文件中。例如在 queries.properties 文件中可以放置上述查询:

update_query=UPDATE user_table SET name=? WHERE id=?

然后借助一个简单的实用程序类:

public class Queries {

private static final String propFileName = "queries.properties";
private static Properties props;

public static Properties getQueries() throws SQLException {
InputStream is =
Queries.class.getResourceAsStream("/" + propFileName);
if (is == null){
throw new SQLException("Unable to load property file: " + propFileName);
}
//singleton
if(props == null){
props = new Properties();
try {
props.load(is);
} catch (IOException e) {
throw new SQLException("Unable to load property file: " + propFileName + "\n" + e.getMessage());
}
}
return props;
}

public static String getQuery(String query) throws SQLException{
return getQueries().getProperty(query);
}

}

您可以按如下方式使用您的查询:

PreparedStatement stm = c.prepareStatement(Queries.getQuery("update_query"));

这是一个相当简单的解决方案,但效果很好。

关于java - 在 Java 中构建 SQL 字符串的最简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/370818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com