我想构建一个 SQL 字符串来执行数据库操作(更新、删除、插入、选择之类的事情) - 而不是使用数百万个“+”和引号的糟糕的字符串连接方法,这充其量是不可读的 - 有一定是更好的方法。
我确实考虑过使用 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"));
这是一个相当简单的解决方案,但效果很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)