使用jdbc實現簡單的使用者登入
阿新 • • 發佈:2019-01-30
1、連線本地MySQL資料庫
test.java
public static Connection getConn() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/xxx";
String username = "root";
String password = "xxx";
Connection conn = null;
try {
Class.forName(driver);
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
2、判斷登入是否成功
test.java
public boolean select(String login,String pass){
Connection conn=test1.getConn();
String sql = "select * from manage where username = '"+login+"'";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement)conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
rs.next(); if(rs.getString("username").equals (login)&&rs.getString("password").equals(pass)){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
第三行String sql = “select * from manage where username = ‘”+login+”’”; 若改成:
String sql = "select * from manage where username = "+login+"";
查詢時則報錯:
Unknown column ‘xxx’ in ‘where clause’
如果查詢的login是整型的話就不會出現錯誤,而如果查詢的login為String型別,則必須要包含在引號內。
3、為button設定監聽器
Login1.java
test t1=new test1();
JButton btnNewButton = new JButton("登入");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(t1.select(login.getText(), new String(pass.getPassword()))){
Login1.this.dispose();
Te frame=new Te();
JOptionPane.showMessageDialog(null, "登入成功", "succeed",JOptionPane.PLAIN_MESSAGE);
frame.setVisible(true);//成功則跳轉到Te.java
}
else {
JOptionPane.showMessageDialog(null,"使用者名稱或密碼輸入錯誤","erro",JOptionPane.ERROR_MESSAGE);
pass.setText("");
}
}
});
第四行 new String ( pass.getPassword () ) 改成 pass.getPassword( ).toString 則報錯
getPassword()的返回值是char[ ],使用了String類的String(char[] chars)構造方法得到字串
第五行Login1.this.dispose();
不能用this.dispose(),因為this表示的是當前物件,指的是實現ActionListener的匿名內部類的物件,為了得到外部類Login1的物件,就必須用Login1.this。