[英]sql prepared statement and java
I am using a Prepared statement which works fine eg if I run我正在使用一个可以正常工作的 Prepared 语句,例如,如果我运行
Select * from users where name = 'john' and sName = sName
I get a list of everyone whose name is john.我得到了一个名字叫约翰的人的名单。 However if I execute the query但是,如果我执行查询
Select * from users where name= ? and sName = ?
the query doesn't return anything, I think it is because it adds the '' to the string being passed?查询不返回任何内容,我认为这是因为它将 '' 添加到正在传递的字符串中?
//n value is passed through GUI interface.
String s = "sName";
PreparedStatement prep = "Select * from users where name= ? and sName= ?";
prep.setString(1, n);
prep.setString(2, s);
Thanks for your help谢谢你的帮助
You are doing it wrong.你做错了。 You must first create a variable of PreparedStatement and initialize it with the query then execute it using executeQuery() method of PreparedStatement .您必须首先创建PreparedStatement的变量并使用查询对其进行初始化,然后使用PreparedStatement 的executeQuery()方法执行它。
It would look like ...它看起来像...
String s = "surname";
String query = "Select * from users where name= ? and surname = ?";
PreparedStatement prep = connection.prepareStatement(query);
prep.setString(1, n);
prep.setString(2, s);
ResultSet rs = prep.executeQuery();
First, note that in首先,请注意,在
Select * from users where name = 'john' and sName = sName
sName=sName
just do nothing if sName
is a column name or does not work.如果sName
是列名或不起作用,则sName=sName
什么也不做。
Then, when you have a statement然后,当你有一个声明
Select * from users where name= ? and surname = ?
You have to set both parameters with PreparedStatement#setXxx()
methods.您必须使用PreparedStatement#setXxx()
方法设置这两个参数。 Since you set the 2d parameter with String s = "surname"
, you will fetch all users that have a surname value which is the string "surname"
, and what ever name you set in the first parameter.由于您使用String s = "surname"
设置了 2d 参数,因此您将获取具有字符串"surname"
的姓氏值的所有用户,以及您在第一个参数中设置的名称。 It looks unlikely, and this is why you get no result.看起来不太可能,这就是为什么你没有结果。
Note1: with this statement you cannot fetch users based only on their name.注意1:使用此语句,您不能仅根据姓名获取用户。 You have to define another statement, eg您必须定义另一个语句,例如
Select * from users where name= ?
Note2: if you have users in the database, without a surname, ie the surname
value is NULL
, then you can use the first statement with注意2:如果数据库中有用户,没有姓氏,即surname
值为NULL
,则可以使用第一个语句
// n variable contains the name
String query = "Select * from users where name= ? and surname = ?";
PreparedStatement prep = connection.prepareStatement(query);
prep.setString(1, n);
prep.setNull(2, Types.VARCHAR);
ResultSet rs = prep.executeQuery();
使用 executeQuery() 而不是 execute()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.