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

新手上路,请多包涵

我想构建一个 SQL 字符串来进行数据库操作(更新、删除、插入、选择等)——而不是使用数百万个“+”和引号的糟糕字符串连接方法,这充其量是不可读的——那里一定是更好的方法。

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

Groovy 会有什么好处吗?

原文由 Vidar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 542
2 个回答

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

 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"));

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

原文由 Piotr Kochański 发布,翻译遵循 CC BY-SA 2.5 许可协议

对于任意 SQL,请使用 jOOQ 。 jOOQ currently supports SELECT , INSERT , UPDATE , DELETE , TRUNCATE , and 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 字符串。看

http://www.jooq.org

(免责声明:我为 jOOQ 背后的公司工作)

原文由 Lukas Eder 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题