JAVA连接SQL server后实现登录界面的代码
时间: 2024-02-28 16:53:22 浏览: 23
下面是一个基于Java Swing和SQL Server的登录界面代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class LoginFrame extends JFrame implements ActionListener {
JLabel userLabel = new JLabel("用户名:");
JLabel passLabel = new JLabel("密码:");
JTextField userText = new JTextField(20);
JPasswordField passText = new JPasswordField(20);
JButton loginButton = new JButton("登录");
public LoginFrame() {
setTitle("登录");
setSize(300, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(10, 10, 10, 10);
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(userLabel, constraints);
constraints.gridx = 1;
panel.add(userText, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
panel.add(passLabel, constraints);
constraints.gridx = 1;
panel.add(passText, constraints);
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
constraints.anchor = GridBagConstraints.CENTER;
panel.add(loginButton, constraints);
getContentPane().add(panel);
loginButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String user = userText.getText();
String pass = new String(passText.getPassword());
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=mydb", "sa", "123456");
pstmt = conn.prepareStatement("select * from users where username=? and password=?");
pstmt.setString(1, user);
pstmt.setString(2, pass);
rs = pstmt.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(this, "登录成功");
dispose();
//TODO: 打开主界面
} else {
JOptionPane.showMessageDialog(this, "用户名或密码错误");
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) {
LoginFrame frame = new LoginFrame();
frame.setVisible(true);
}
}
```
这个示例使用了JDBC连接到SQL Server数据库,并在登录按钮上添加了一个ActionListener,该Listener检查提供的用户名和密码是否与数据库中的记录匹配。如果匹配,则显示一个消息框,然后关闭登录窗口并打开主窗口。否则,它将提示用户名或密码错误。