我正在尝试制作一个登录程序,我需要将 GUI 中的用户名/密码交叉引用到数据库中,我目前有代码,但它只是对相同数量的人说“用户名/密码不正确!”在数据库中。真正使它工作的任何帮助都会很棒。我的代码如下。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Login extends JFrame {
JTextField _username = new JTextField(10);
JPasswordField _password = new JPasswordField(10);
JButton _login = new JButton("Login");
JButton _exit = new JButton("Exit");
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenHeight = (int)screenSize.getHeight();
int screenWidth = (int)screenSize.getWidth();
public Login() {
super("Login to panel");
setLayout(new GridLayout(3,2,1,1));
add(new JLabel("Username:"));
add(_username);
add(new JLabel("Password:"));
add(_password);
add(_login);
_login.addActionListener(new LoginListener());
add(_exit);
_exit.addActionListener(new ExitListener());
setSize(250, 100);
//setLocation(screenWidth/3, screenHeight/3);
setLocation(500, 400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Login();
}
public class LoginListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Connection con;
Statement stmt;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:collegesys","root","0blivi0n");
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT * FROM main");
PreparedStatement loginTime = con.prepareStatement("UPDATE `main` WHERE ID = ?");
while(rs.next()) {
if(_username.getText() == rs.getObject("username") && _password.getText() == rs.getObject("password")) {
dispose();
new Panel();
} else {
JOptionPane.showMessageDialog(null, "Incorrect Username/Password!");
}
}
} catch(SQLException sqle) {
sqle.printStackTrace();
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
}
}
public class ExitListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
dispose();
System.exit(0);
}
}
}