用Java语言实现一个可视化登录注册页面与mysql数据库相连
时间: 2024-03-12 16:46:24 浏览: 17
好的,以下是一个简单的Java Swing登录注册页面,并与MySQL数据库相连的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.sql.*;
public class LoginRegistration extends JFrame {
// 定义组件
JLabel usernameLabel;
JLabel passwordLabel;
JTextField usernameField;
JPasswordField passwordField;
JButton loginButton;
JButton registrationButton;
JPanel panel;
Connection conn;
public LoginRegistration() {
// 初始化组件
usernameLabel = new JLabel("用户名:");
passwordLabel = new JLabel("密码:");
usernameField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton("登录");
registrationButton = new JButton("注册");
panel = new JPanel();
// 添加组件
panel.add(usernameLabel);
panel.add(usernameField);
panel.add(passwordLabel);
panel.add(passwordField);
panel.add(loginButton);
panel.add(registrationButton);
// 设置窗口属性
setTitle("登录/注册");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 添加面板
add(panel);
// 添加事件监听器
loginButton.addActionListener(e -> {
String username = usernameField.getText();
String password = String.valueOf(passwordField.getPassword());
try {
// 连接数据库
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
// 查询语句
String sql = "SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'";
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
if (rs.next()) {
JOptionPane.showMessageDialog(null, "登录成功!");
} else {
JOptionPane.showMessageDialog(null, "用户名或密码错误!");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
});
registrationButton.addActionListener(e -> {
String username = usernameField.getText();
String password = String.valueOf(passwordField.getPassword());
try {
// 连接数据库
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
// 插入语句
String sql = "INSERT INTO users (username, password) VALUES ('" + username + "', '" + password + "')";
Statement statement = conn.createStatement();
statement.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "注册成功!");
} catch (SQLException ex) {
ex.printStackTrace();
}
});
}
public static void main(String[] args) {
LoginRegistration loginRegistration = new LoginRegistration();
loginRegistration.setVisible(true);
}
}
```
在这个示例中,我们使用了Java的Swing库来创建一个简单的登录/注册窗口。当用户点击"登录"按钮时,程序会尝试连接MySQL数据库,并查询用户名和密码是否匹配。当用户点击"注册"按钮时,程序会尝试连接MySQL数据库,并将用户名和密码插入到"users"表中。
请注意,这个示例代码只是一个简单的演示,实际应用中需要更多的安全性和数据验证。