创建用户登录程序,验证用户账号和密码信息是否在数据库student中的用户表tb_account中存在。用户登录界面如下图所示:
当单击“登录”按钮时,处理以下几种情况:
(1)用户名未输入,提示用户名不能为空;
(2)密码未输入,提示密码不能未空;
(3)用户名输入错误或者密码输入错误(在tb_account表中查询不到该用户id和密码),提示用户名或密码错误;
(4)用户名和密码输入都正确(在tb_account表中能查询到该用户id和密码),提示登录成功。
完整代码如下:
1.首先建立databaseConnection类,代码如下:
import java.sql.*;
import java.awt.*;
import javax.swing.*;
public class databaseconnection {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/student";
static final String USER = "root";
static final String PASS = "123456";
public static boolean checkCredentials(String userId, String password) {
Connection conn = null;
boolean isValid = false;
try {
// 加载 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 建立连接
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// SQL 查询
String sql = "SELECT COUNT(*) FROM tb_account WHERE user_id = ? AND password = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, userId);
pstmt.setString(2, password);
ResultSet resultSet = pstmt.executeQuery();
if (resultSet.next()) {
int count = resultSet.getInt(1);
isValid = count > 0;
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return isValid;
}
}
2.然后建立LoginFrame类,代码如下:
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginFrame extends JFrame {
private JTextField userIdField;
private JPasswordField passwordField;
private JButton loginButton;
public LoginFrame() {
super("用户登录");
createUI();
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void createUI() {
setLayout(new FlowLayout());
userIdField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton("登录");
add(new JLabel("账号:"));
add(userIdField);
add(new JLabel("密码:"));
add(passwordField);
add(loginButton);
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
performLogin();
}
});
}
private void performLogin() {
String userId = userIdField.getText();
String password = new String(passwordField.getPassword());
if (userId.isEmpty()) {
JOptionPane.showMessageDialog(this, "用户名不能为空", "错误", JOptionPane.ERROR_MESSAGE);
} else if (password.isEmpty()) {
JOptionPane.showMessageDialog(this, "密码不能为空", "错误", JOptionPane.ERROR_MESSAGE);
} else {
boolean loginSuccess = databaseconnection.checkCredentials(userId, password);
if (loginSuccess) {
JOptionPane.showMessageDialog(this, "登录成功", "成功", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "用户名或密码错误", "错误", JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) {
new LoginFrame();
}
}