我想构建一个SQL字符串来执行数据库操作(更新、删除、插入、选择,诸如此类的事情)-而不是使用数百万个“+”和引号的糟糕的字符串连接方法,这充其量是不可读的-必须有更好的方法。
我确实考虑过使用MessageFormat,但它应该用于用户消息,尽管我认为它可以做一些合理的工作,但我猜java SQL库中应该有一些更符合sql类型操作的东西。
Groovy会有什么好用吗?
发布于 2008-12-16 10:15:44
首先,考虑在准备好的语句中使用查询参数:
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"));
这是一个相当简单的解决方案,但效果很好。
发布于 2011-08-09 14:33:54
对于任意SQL,请使用jOOQ。jOOQ目前支持SELECT
、INSERT
、UPDATE
、DELETE
、TRUNCATE
和MERGE
。您可以像这样创建SQL:
String sql1 = DSL.using(SQLDialect.MYSQL)
.select(A, B, C)
.from(MY_TABLE)
.where(A.equal(5))
.and(B.greaterThan(8))
.getSQL();
String sql2 = DSL.using(SQLDialect.MYSQL)
.insertInto(MY_TABLE)
.values(A, 1)
.values(B, 2)
.getSQL();
String sql3 = DSL.using(SQLDialect.MYSQL)
.update(MY_TABLE)
.set(A, 1)
.set(B, 2)
.where(C.greaterThan(5))
.getSQL();
您也可以使用jOOQ直接执行它,而不是获取SQL字符串。看见
(免责声明:我为jOOQ背后的公司工作)
https://stackoverflow.com/questions/370818
复制相似问题