我试图用Java(在j创建者中)检查用户名和密码,但是无法正确使用语法。 如何通过传递用户名和密码在数据库中实现简单检查?以下是解决问题的代码:
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;
答案 0 :(得分:1)
您需要按以下方式更改查询 -
String sql = "SELECT * from operators where user_name = ? and pass_word = ?";
?
是setXXX(索引,值)方法替换的内容。
答案 1 :(得分:0)
我只需要将SQL查询字符串更改为下面的内容即可传递参数!卫生署!
String sql = "SELECT * from operators where user_name = ? and pass_word = ?";