Java从数据库中选择where where condition

时间:2014-11-03 10:27:37

标签: java mysql

我有一个问题。在我的方法

public void  selectUser(String name, String surname)

我尝试登录用户。我如何准备像这样的sql语句:

String sql = "select * from user where surname= (here my surname from method parameter) and name= (name from method parameter)  ";

2 个答案:

答案 0 :(得分:2)

初始化您的PreparedStatement对象

PreparedStatement pst = null;
pst = c.prepareStatement("select * from user where surname= ? and name= ? ");
            pst.setString(1, getterMethodHere);
            pst.setString(2, getterMethodHere);

1,2分别代表surname= ? and name= ?符号

Learn More . .

答案 1 :(得分:0)

圣克里希谢谢。现在如何使用rs.next,因为我不了解prepareStatemnt。

这是代码

enter code here  



        //stat = con.createStatement();
        //String sql = "select * from user where surname= "+surname+" and name="+name;
        PreparedStatement pst = null;
        pst = con.prepareStatement("select * from user where surname= ? and name= ? ");
        pst.setString(1, name);
        pst.setString(2, surname);
        ResultSet rs = pst.executeQuery();



        while (rs.next()) {
            //get from column name

            String id = rs.getString("id");
            String login = rs.getString("login");
            String password = rs.getString("password");

            //print

            System.out.print(" id: " + id);
            System.out.print(", login: " + login);
            System.out.println(", pass: " + password);
        }

以及如何返回id?