如何使用变量作为WHERE执行SQL语句?

时间:2012-02-03 02:53:39

标签: java sql jdbc

我有一些像

这样的Java代码
int userid = take user input;

然后执行以下sql语句,

        Class.forName(dbdriver);
        conn = DriverManager.getConnection(url, username, password);
        st = conn.createStatement();

        st.executeUpdate("select * from person where uid = userid" );

现在,我不知道返回的结果是null。我认为where uid = userid给出了错误的结果,因为它正在搜索文字的uid值“userid”。实际上,我想从人员表中检索有关用户提供的uid值的信息。任何人都可以帮我解决这个问题吗?

4 个答案:

答案 0 :(得分:7)

您应该使用prepare语句,因为它可以保护您免受sql注入。您还可以通过在执行之前打印出sql语句来添加简单的日志记录,这样您就可以确定了。下面是示例课程,但您可以随意更改它。

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;        
    }

}

答案 1 :(得分:5)

你可以粘贴关于这个问题的整个代码块吗? 以下是我的建议

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);

如果数据库有一个或多个记录,其中uid字段等于userid,则返回正确的结果

答案 2 :(得分:5)

ResultSet rs = stmd.executeQuery("select * from person where uid = "+ userid);

while (rs.next()) {
    System.out.println("Name= " + rs.getString(1));
}

答案 3 :(得分:-1)

int user_id = 2003; //你也可以得到输入变量

String sql =“SELECT * FROM employment WHERE id =”;

resultSet = statement.executeQuery(sql + user_id);