如何去掉 java sql 语句中的许多占位符(问号)

How to get rid of many placeholders (question marks) in java sql statements

我想使用 JDBC 在 table 中插入一行。但是 table 有很多列,所以我不想将它们全部指定到一个语句中。还有另一种指定列值的方法吗?

INSERT INTO TABLE_NAME VALUES(?, ?, ?, ..., ?)

我希望有另一种方法可以不用大量的占位符。

已编辑:

我的意思是,我可以像 ... 那样编辑查询吗,这意味着它需要很多值并使用递增索引或其他方式动态设置值。是的,正如@f1sh 提到的,问题出在占位符的数量上,但在 懒惰 的情况下不是,更多的是在方便和清洁的情况下。

P.S.: 由于某些 有趣的企业需求 原因,我无法使用 JPA 框架 :)

编辑

另一种选择是自己编写或使用 SqlBuilder

SqlBuilder changes that whole scenario by wrapping the SQL syntax within very lightweight and easy to use Java objects which follow the "builder" paradigm (similar to StringBuilder). This changes many common SQL syntactical, runtime errors into Java compile-time errors! Let's dive right in to some quick examples to to see how it all works.

您可以使用 Spring 的 NamedParameterJdbcTemplate 并使用变量名

String SQL = INSERT INTO TABLE_NAME VALUES((:id),...);

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("id", "idValue");
//...
namedParameterJdbcTemplate.update(SQL, parameters) > 0;

Template class with a basic set of JDBC operations, allowing the use of named parameters rather than traditional '?' placeholders.

如果您可以(安全地)使用 dynamic query 使用 Statement:

Statement stmt = (Statement) con.createStatement(“SELECT username, password FROM users WHERE username='” + user + “‘ AND password='” + pass + “‘ limit 0,1”);

ResultSet rs = stmt.executeQuery();

您只能在封闭值上使用它,因此没有 SQL 注入选项