use*_*206 2 java database swing login jdbc
我似乎无法在我的Java JTextfield和Passwordfield上获取密码和用户名,我试图做的是比较用户输入并检查它们是否存储在数据库中的用户名和密码,如果是这样,他们将被登录,但问题是我的密码字段上的getText()已弃用,我该如何修复?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.JOptionPane;
public class Login extends JFrame {
private JLabel nameLabel;
private JLabel passwordLabel;
private JTextField nameText;
private JPasswordField passwordField;
private JButton submitButton;
Connection conn = null;
public Login(){
super("Log in!");
setLayout(new FlowLayout());
setVisible(true);
setSize(178,190);
setDefaultCloseOperation(EXIT_ON_CLOSE);
nameLabel = new JLabel("User ID: ");
add(nameLabel);
nameText = new JTextField(10);
add(nameText);
passwordLabel = new JLabel("Password: ");
add(passwordLabel);
passwordField = new JPasswordField(10);
add(passwordField);
submitButton = new JButton("Submit");
add(submitButton);
ButtonHandler handler = new ButtonHandler();
submitButton.addActionListener(handler);
}
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
String user = nameText.getText();
String pass = passwordField.getText();
try{
Jdbc test = new Jdbc();
conn = test.dbConn();
String query = "SELECT employee_ID,employee_password FROM user where ='"+user+"'";
}catch(Exception eee){
eee.printStackTrace();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用getPassword()而不是getText()方法.
char []passChars=passwordField.getPassword();
if(passChars!=null) {
String pass=new String(passChars);
String sql="SELECT employee_ID,employee_password FROM user
where user=? and employee_password=?";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,user);
ps.setString(2,pass);
ResultSet rs=ps.executeQuery();
if(rs.next()) {
//found
}
else{
//not found
}
rs.close();
ps.close();
conn.close();
}
Run Code Online (Sandbox Code Playgroud)
值得注意的一点是,不要使用硬编码的sql语句.使用PreparedStatement逃生绳,以防止SQL注入.