【发布时间】:2014-09-18 14:35:23
【问题描述】:
我正在尝试制作一个连接到 SQL 数据库的登录表单。这是我的代码:
private void cmd_loginActionPerformed(java.awt.event.ActionEvent evt) {
String sql="Selet * from inventor1";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= (Connection);
DriverManager.getConnection("jdbc:mysql://localhost:3306/inventor","root","root");
Statement stmt=conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
String user=t1.getText();
String pass=new String(t2.getText());
while(rs.next()){
String username=rs.getString("username");
String password=rs.getString("password");
if(user.equals("username") && pass.equals("password")){
new Mainmenu().setVisible(true);
}
}
}catch(Exception e){
JOptionPane.showMessageDialog(this, "password and username not match");
}
}
但是,用户名和密码似乎永远不会匹配,即使我输入的内容与数据库中的内容匹配。为什么用户名和密码永远不匹配?
【问题讨论】:
-
只需打印
e.printStackTrace()即可查看您遇到的任何异常。您正在跳过它(这是一种不好的做法) -
您的真实程序是否在
sql字符串中显示“selet”?我认为那应该是“选择”。 -
为什么要选择数据库中的所有行并通读所有行以找到匹配项?那不是很有效。相反,您应该使用带有 where 子句的 select 语句来匹配您的用户 ID 和密码。您可以先阅读JDBC Database Access 上的一些 SQL 基础教程。
-
如果我们讨论的是存储登录信息的最佳做法,请不要忘记散列密码!