Java连接SQL数据库实现登陆

时间:2021-01-26 09:44:25
【文件属性】:

文件名称:Java连接SQL数据库实现登陆

文件大小:3KB

文件格式:JAVA

更新时间:2021-01-26 09:44:25

Java MySQL JFrame

package cn; import java.awt.*; import java.awt.event.*; import java.sql.*; import javax.swing.*; //登陆面板 public class Login extends JFrame { Connection conn = null; Statement stmt = null; ResultSet rst = null; public Login() { try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("加载驱动成功。"); String url = "jdbc:mysql://localhost/users"; String user = "root"; String password = "123456"; conn = DriverManager.getConnection(url, user, password); System.out.println("连接数据库成功。"); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rst = stmt.executeQuery("SELECT*FROM user"); } catch (Exception e) { System.out.println(e); } setTitle("登陆页面"); JPanel panel = new JPanel(); //JLabel lblName = new JLabel("用户名:"); JTextField txtName = new JTextField(10); //lblName.setHorizontalAlignment(JLabel.CENTER); panel.add(new JLabel("用户名:")); panel.add(txtName); JLabel lblPassword = new JLabel("密码:"); JPasswordField txtPassword = new JPasswordField(10); lblPassword.setHorizontalAlignment(JLabel.CENTER); panel.add(lblPassword); panel.add(txtPassword); add(panel, BorderLayout.CENTER); JPanel panel2 = new JPanel(); JButton btnLogin = new JButton("登陆"); /** * 给登陆按钮添加监听事件 当按钮被点击时时间被触发 */ btnLogin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean b = false; // boolean b = um.Login(txtName.getText(), txtPassword.getText()); try { stmt = conn.createStatement();// 预定义语句 // 数据库查询语句(根据用户名和密码) String sql = "select * from user where User='" + txtName.getText() + "' and Password='" + txtPassword.getText() + "'"; rst = stmt.executeQuery(sql);// 执行查询语句 // rst中有数据,则将标记改为true if (rst.next()) { b = true; } } catch (SQLException e1) { e1.printStackTrace(); } if (b) {// 登陆成功,跳转页面 JOptionPane.showMessageDialog(null, "登陆成功!"); new ProductQueryDemo();// 打开主页 dispose();// 关闭窗口 } else {// 登陆失败 JOptionPane.showMessageDialog(null, "登陆失败!"); } } }); JButton btnReset = new JButton("重置"); /** * 点击重置按钮时,将文本框中的值设置为空 */ btnReset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { txtName.setText(""); txtPassword.setText(""); } }); JButton btnSignin = new JButton("注册"); /** * 点击注册按钮时,调用注册程序 */ btnSignin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new Signin(); dispose();// 关闭窗口 } }); panel2.add(btnLogin); panel2.add(btnReset); panel2.add(btnSignin); add(panel2, BorderLayout.PAGE_END); setSize(430, 150); setLocationRelativeTo(null); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new Login(); } }


网友评论