0

我试图检查 Java 中的用户名和密码(在 j creator 中),但无法正确使用语法。如何通过传递用户名和密码来实现对数据库的简单检查?这是让我遇到问题的代码:

      try
    {
String userN, passW, host, database;
userN = "Michael";
passW = "Blaine22";
host = "localhost";
database = "maintenance_work";

        Connection conn = DriverManager.getConnection
    ("jdbc:mysql://"+host+":3306/"+database, userN, passW);

    conn.setAutoCommit(false);
    ResultSet rs = null;
    PreparedStatement pst = null;

    Boolean user_Check_pass;

    String sql =("SELECT * from operators where user_name = " + user + " and pass_word= " + pass);

        pst = conn.prepareStatement(sql);

        pst.setString(1, user);
        pst.setString(2, pass);
        rs = pst.executeQuery();

        if (rs.next())
        {
             System.out.println ("Username and Password correct");
             user_Check_pass = true;
        }
        else
        {
              System.out.println ("invalid username and password");
               user_Check_pass = false;
        }
    }
   catch (SQLException e)
   {
    e.printStackTrace();
}
    return false;
4

2 回答 2

1

您需要按如下方式更改您的查询 -

String sql = "SELECT * from operators where user_name = ? and pass_word = ?";

?s 是 setXXX(index, value) 方法所取代的。

于 2014-04-18T18:32:55.690 回答
0

为了传递参数,我只需要将 SQL 查询字符串更改为以下!嗬!

String sql = "SELECT * from operators where user_name = ? and pass_word = ?";
于 2014-04-18T18:33:18.083 回答