帮我写一份Java代码gui页面窗口登录账号密码是连接MySQL数据库的
时间: 2024-02-05 14:10:57 浏览: 24
好的,以下是一个简单的Java GUI页面窗口登录账号密码并连接MySQL数据库的代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class LoginGUI extends JFrame {
private JLabel usernameLabel, passwordLabel;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton;
public LoginGUI() {
super("Login");
setLayout(new GridLayout(3, 2));
usernameLabel = new JLabel("Username:");
passwordLabel = new JLabel("Password:");
usernameField = new JTextField();
passwordField = new JPasswordField();
loginButton = new JButton("Login");
add(usernameLabel);
add(usernameField);
add(passwordLabel);
add(passwordField);
add(loginButton);
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = String.valueOf(passwordField.getPassword());
try {
// connect to MySQL database
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
// check if user exists
PreparedStatement statement = conn.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?");
statement.setString(1, username);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
if (result.next()) {
JOptionPane.showMessageDialog(null, "Login successful!");
} else {
JOptionPane.showMessageDialog(null, "Invalid username or password.");
}
conn.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setVisible(true);
}
public static void main(String[] args) {
new LoginGUI();
}
}
```
在这个示例中,我们使用了Swing库来创建GUI窗口,包括标签、文本框和按钮。当用户点击登录按钮时,我们通过JDBC连接到MySQL数据库,执行一个查询语句来验证用户输入的用户名和密码是否正确。如果查询结果存在,我们弹出一个对话框来显示“登录成功”消息;否则,我们弹出一个对话框来显示“无效的用户名或密码”消息。
请注意,在这个示例中,我们假设MySQL数据库已经安装在本地主机上,并且数据库名为“mydatabase”,用户名为“root”,密码为“password”。如果您的实际情况不同,请根据实际情况修改连接字符串和查询语句。