java登录系统代码,要求使用GUI和链接数据库
时间: 2024-02-28 13:53:33 浏览: 19
以下是一个简单的Java登录系统代码,使用GUI和连接数据库(MySQL):
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class LoginSystem extends JFrame implements ActionListener {
JTextField usernameField;
JPasswordField passwordField;
JButton loginButton;
Connection conn;
public LoginSystem() {
// 设置窗口标题和大小
setTitle("Login System");
setSize(300, 200);
// 设置窗口布局
setLayout(new GridLayout(3, 2));
// 添加用户名和密码输入框
add(new JLabel("Username:"));
usernameField = new JTextField();
add(usernameField);
add(new JLabel("Password:"));
passwordField = new JPasswordField();
add(passwordField);
// 添加登录按钮
loginButton = new JButton("Login");
loginButton.addActionListener(this);
add(loginButton);
// 初始化数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "password");
} catch (Exception e) {
e.printStackTrace();
}
// 显示窗口
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
// 获取输入的用户名和密码
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
// 查询用户信息
try {
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?");
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(this, "Login successful!");
} else {
JOptionPane.showMessageDialog(this, "Invalid username or password.");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new LoginSystem();
}
}
```
这个代码创建了一个GUI窗口,让用户输入用户名和密码,并在点击登录按钮时验证用户信息。它使用了Java的JDBC API来连接MySQL数据库,并使用PreparedStatement来防止SQL注入攻击。在实际使用中,你需要根据你的数据库配置修改代码中的连接字符串、用户名和密码。