[英]How to execute a SQL statement with a variable as WHERE?
I have some Java code like 我有一些Java代码
int userid = take user input;
And then execute following sql statement, 然后执行以下sql语句,
Class.forName(dbdriver);
conn = DriverManager.getConnection(url, username, password);
st = conn.createStatement();
st.executeUpdate("select * from person where uid = userid" );
Now, I don't know the returned result is null
. 现在,我不知道返回的结果是null
。 I think where uid = userid
is giving wrong result because it is searching for literal uid value "userid". 我认为where uid = userid
给出了错误的结果,因为它正在搜索文字uid值“userid”。 Actually, I want to retrive information from person table about user provided uid values. 实际上,我想从人员表中检索有关用户提供的uid值的信息。 Can anybody help me how to solve this? 任何人都可以帮我解决这个问题吗?
You should use prepare statement as it protect you from sql injection. 您应该使用prepare语句,因为它可以保护您免受SQL注入。 You can also add a simple logging by printing out the sql statement before it is executed and so you are sure. 您还可以通过在执行之前打印出sql语句来添加简单的日志记录,这样您就可以确定了。 Below is the example class but feel free to change it in your situation. 以下是示例课程,但您可以随意更改它。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DBAccess
{
PreparedStatement pstmt;
Connection con;
DBAccess() throws Exception
{
String dbdriver = "";
String url = "";
String username = "";
String password = "";
Class.forName(dbdriver);
con = DriverManager.getConnection(url, username, password);
}
public Person getPerson(int userid) throws Exception
{
pstmt = con.prepareStatement("select * from person where uid = ?");
pstmt.setInt(1, userid);
System.out.println("sql query " + pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
Person person = new Person();
person.setName(rs.getString("name"));
return person;
}
return null;
}
}
Could you paste the whole code block about this question? 你可以粘贴关于这个问题的整个代码块吗? Following is my suggestion 以下是我的建议
int userid = get user id ;
Connection connection = get connection ;
String sql = "select * from person where uid=?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1,userid);
if the database has one or more record which is uid filed equal the userid ,that will return the correct result 如果数据库有一个或多个uid字段等于userid的记录,则返回正确的结果
ResultSet rs = stmd.executeQuery("select * from person where uid = "+ userid);
while (rs.next()) {
System.out.println("Name= " + rs.getString(1));
}
int user_id=2003; int user_id = 2003; // you can also get input variable //你也可以得到输入变量
String sql="SELECT * FROM employment WHERE id="; String sql =“SELECT * FROM employment WHERE id =”;
resultSet = statement.executeQuery(sql+user_id); resultSet = statement.executeQuery(sql + user_id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.