JDBC连接Mysql数据库---实现登录注册功能

1.1 效果图演示

JDBC连接Mysql数据库---实现登录注册功能_第1张图片

1.2 数据准备

CREATE TABLE USER (
  id INT AUTO_INCREMENT PRIMARY KEY,
  NAME VARCHAR(50),
  PASSWORD VARCHAR(50)
);
INSERT INTO USER (NAME, PASSWORD) VALUES('admin', '123'), ('test', '123'), ('gm', '123');

1.3 代码实现

  • 工具类
package Utils;

import java.sql.*;
import java.util.Collection;
/*
    工具类
 */
public class JDBCUtils {

    public static final String DIVERCLASS = "com.mysql.jdbc.Driver";
    public  static final String URL = "jdbc:mysql://localhost:3306/test";
    public static  final String USER = "root";
    public static  final String PASSWORD = "root";

    //每次别人获取连接的时候,都需要加载该类。但是一个类只需要加载一次就够了。静态代码块只需要执行一次。
    static {
        try {
            Class.forName(DIVERCLASS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
           connection = DriverManager.getConnection(URL,USER,PASSWORD);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //关闭资源
    public static void close(ResultSet rs, Statement  st,Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
package com.enjoy.test;

import Utils.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

public class LoginTest {
    public static void main(String[] args)throws Exception {
        //创建扫描器
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入账号:");
        String userName = sc.nextLine();
        System.out.println("请输入密码:");
        String password = sc.nextLine();
        boolean flag = login(userName,password);
        if(flag){
            System.out.println("恭喜"+userName+"登录成功");
        }else {
            System.out.println("账号或密码错误或不存在");
        }
    }

    private static boolean login(String userName, String password) throws Exception {
        //获取对象
        Connection connection = JDBCUtils.getConnection();
        //获取SQL运输器
        String sql = "select*from user where name=? and password=?";
        //得到预编译对象
        PreparedStatement pst = collection.prepareStatement(sql);
        //给?赋值
        pst.setString(1,userName);
        pst.setString(2,password);
        //执行SQL
        ResultSet rs = pst.executeQuery();
        return rs.next();
    }
}

 

你可能感兴趣的:(JDBC)