举一个我的问题的简单例子:
//Create database table allowing nulls.
CREATE TABLE test(one int not null, two int null, three int not null);
现在,在 Java 中,我有一组与数据库内容匹配的对象。我需要使用数组值为此数据库表创建插入/更新/删除语句。
Object[] arr = { 4, null, 1 };
String sql = GenereateInsert(arr);
但这变得很困难,因为我需要提前从插入中删除空字段。例如。如果上面的两个不为空:
INSERT INTO test(4, 2, 1);
一切都很简单。但如果它为空,我需要声明为:
INSERT INTO test(one, three) values(4, 1);
我正在处理的表有 50 列及以上,所以我不想手动执行此操作,这将难以管理。那么,人们通常如何解决这个问题呢?这一定是常见的情况。
PS:我不想使用完整的 ORM 库,这看起来有点矫枉过正。
最佳答案
我会建议这样的事情:
运行类似
SELECT * FROM <TABLE_NAME> LIMIT 1
的查询.使用ResultSetMetaData
检索 columnNames 及其 columnType。将其存储在 HashMap 中,将键存储在 ArrayList 中现在创建一个
PreparedStatement
使用 ArrayList 中的键作为列名。 我想这并不难现在给定数组中的数据,您知道它们来自 HashMap 的 SQL 类型这一事实,您可以轻松地使用此信息将从数组中获得的值映射到
?
中。您生成的 PreparedStatement。
现在的问题是如何处理null
.既然你知道列的类型,如果你得到的值是 null
那么你可以使用 PreparedStatement.setNull(...)
将它们设置为空。
此外,我只想指出 according to this document ,有一个关于 JDBC 的 setXXX(...) 的重要指南:
6.1.5 Sending JDBC NULL as an IN parameter
The setNull method allows a programmer to send a JDBC NULL (a generic SQL NULL) value to the database as an IN parameter. Note, however, that one must still specify the JDBC type of the parameter.
A JDBC NULL will also be sent to the database when a Java null value is passed to a setXXX method (if it takes Java objects as arguments). The method setObject, however, can take a null value only if the JDBC type is specified.
这意味着您可以发送 null 作为 setXX(...)
的参数值方法,您真的不必调用 setNull(..)
显式方法。
我希望这对你有用!
关于java - 从具有空值的数组动态填充 Java 中的 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12430213/