我想构建一个SQL字符串来进行数据库操作(更新、删除、插入、 Select ,诸如此类的事情)——而不是使用数百万个"+"和引号的糟糕的字符串concat方法,这最多是不可读的——必须有更好的方法.
我确实想过使用MessageFormat——但它应该用于用户消息,尽管我认为它会做一个合理的工作——但我想java SQL库中应该有更符合SQL类型操作的东西.
Groovy有什么好处吗?
我想构建一个SQL字符串来进行数据库操作(更新、删除、插入、 Select ,诸如此类的事情)——而不是使用数百万个"+"和引号的糟糕的字符串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();
可以做的另一件事是将所有查询保存在属性文件中.例如
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"));
这是一个相当简单的解决方案,但效果很好.