请帮助我想知道如何在mysql数据库的文本域中比较用户输入的用户名和密码.....我正在使用netbeans IDE 这是我的代码:
String a,b;
a=txtusername.getText();
b=new String(txtpassword.getPassword());
try
{
Class.forName("java.sql.DriverManager");
Connection conn=(Connection) DriverManager.getConnection
("jdbc:mysql://localhost:3306/project","root","pizza123");
Statement stmt=(Statement) conn.createStatement();
String query1="select username from userdata where username='"+a+"';";
String query2="select password from userdata where password='"+b+"';";
ResultSet rs1=stmt.executeQuery(query1);
ResultSet rs2=stmt.executeQuery(query2);
if(a.equals(rs1.getString(query1)) || b.equals(rs2.getString(query2)))
{
close();
tickets x= new tickets();
x.setVisible(true);
}
else
{
JOptionPane.showMessageDialog(this,"Username or Password is incorrect");
}
}
catch(ClassNotFoundException | SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
答案 0 :(得分:0)
向数据库发送查询
SELECT * FROM userdata WHERE username = @username, password = @password;
用户参数添加@username and @ password
的值,否则可以使用sql注入。如果被感染的行> 0然后你有一个成功的登录
答案 1 :(得分:0)
语句rs1.getString(query1)和rs2.getString(query2)无效。 从结果集对象中,您可以使用列索引或列名称检索其当前行值。 在您的情况下,您可以编写rs1.getString(" username")或rs1.getString(1),因为在JDBC中,世界索引从一开始。
无论如何,更好的解决方案可能是这个
String a,b;
a = txtusername.getText();
b = new String(txtpassword.getPassword());
PreparedStatement statement = null;
Connection conn = null;
try {
Class.forName("java.sql.DriverManager");
Connection conn=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","pizza123");
String query = "select * from userdata where username = ? and password = ?";
statement = conn.prepareStatement(query);
statement.setString(1, a);
statement.setString(2, b);
ResultSet rs = statement.executeQuery();
//check if you have found a valid row
if(rs.next()) {
close();
tickets x= new tickets();
x.setVisible(true);
} else {
JOptionPane.showMessageDialog(this,"Username or Password is incorrect");
}
} catch(ClassNotFoundException | SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(this, e.getMessage());
} finally {
try {
if(statement != null)
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
try {
if(conn != null)
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
此解决方案使用PreparedStatement来防止SQLInjection攻击。使用finally块,您肯定会释放语句和连接。