[英]Using Java's JDBC PreparedStatement on a SQLite Database to query for NOT NULL
I'm new to PreparedStatement in Java, and I can't seem to figure out an optimal solution to my problem. 我是Java中PreparedStatement的新手,似乎无法找出解决问题的最佳方法。 I want to query for records in a table that are either NULL, or NOT NULL.
我想查询表中为NULL或NOT NULL的记录。
When reading PreparedStatement (Java Platform SE 6) , I realized that I needed to use the setNull method, but I did not see a way to set NOT NULL? 在阅读PreparedStatement(Java Platform SE 6)时 ,我意识到我需要使用setNull方法,但没有看到设置NOT NULL的方法?
For example: 例如:
SELECT * FROM table WHERE column IS NULL
What I assume I would do is: 我想我会做的是:
public void query(boolean getNull) {
String querySql = "SELECT * FROM table WHERE column IS ?";
sqlStatement = connection.prepareStatement(querySql);
if(getNull)
sqlStatement.setNull(1, Types.VARCHAR);
else
???;
}
But how would I do the else statement? 但是,我将如何做else语句? There is not a setNotNull method.
没有setNotNull方法。 I assume I could do this:
我认为我可以这样做:
public void query(boolean getNull) {
String querySql = "SELECT * FROM table WHERE column IS ? NULL";
sqlStatement = connection.prepareStatement(querySql);
sqlStatement.setString(1, (getNull ? "" : "NOT"));
}
But that seems very 'hackish.' 但这似乎很“骇人”。 Is there any better way to do this?
有什么更好的方法吗?
Thank you 谢谢
? ? is for passing paramters, not building a SQL.
用于传递参数,而不是构建SQL。 ( taken partially from here )
( 部分取自此处 )
I suggest you to use parameters only for values, not fields or [IS] NULL
(anything like that). 我建议您仅对值使用参数,而不对字段或
[IS] NULL
(类似的东西)使用参数。
Just concatenate the Strings. 只需串联字符串即可。 If you has more than one parameter you should take a look at
StringBuilder
. 如果您有多个参数,则应查看
StringBuilder
。
public void query(boolean getNull) {
String querySql = "SELECT * FROM table WHERE column IS ";
if(getNull) {
querySql += "NULL";
} else {
querySql += "NOT NULL";
}
sqlStatement = connection.prepareStatement(querySql);
}
also a possible way can be using String.format(...)
, as example: 也可以使用
String.format(...)
作为示例,例如:
public void query(boolean getNull) {
String querySql = String.format("SELECT * FROM table WHERE column IS %s NULL", (getNull ? "" : "NOT"));
sqlStatement = connection.prepareStatement(querySql);
}
One way to do it would be to look at the resultset that is returned by the query: 一种方法是查看查询返回的结果集:
"SELECT * FROM table WHERE column IS ?"
Use your PreparedStatement to set the value to NULL and then execute the query. 使用PreparedStatement将值设置为NULL,然后执行查询。 You can use the
resultset.next()
to test out what you're looking for. 您可以使用
resultset.next()
来测试所需的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.