写出java代码,查找键盘输入到JPasswordField的一串数字是否在所连接的数据库中,
时间: 2024-02-21 22:58:25 浏览: 61
好的,以下是一个简单的 Java 代码示例,可以实现您的要求:
```java
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class PasswordChecker extends JFrame implements ActionListener {
private JLabel label;
private JPasswordField passwordField;
private JButton button;
private Connection conn = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
public PasswordChecker() {
super("Password Checker");
label = new JLabel("Please enter your password:");
passwordField = new JPasswordField(20);
button = new JButton("Check");
button.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(label);
panel.add(passwordField);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttonPanel.add(button);
Container container = getContentPane();
container.add(panel, BorderLayout.NORTH);
container.add(buttonPanel, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String password = new String(passwordField.getPassword());
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
String sql = "SELECT * FROM passwords WHERE password = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, password);
rs = ps.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(this, "Password is correct!");
} else {
JOptionPane.showMessageDialog(this, "Password is incorrect!");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new PasswordChecker();
}
}
```
请注意,这只是一个简单的示例,需要根据您的具体需求进行修改和优化。此外,为了使代码更加安全,建议使用加密算法对密码进行编码和解码。
阅读全文