Java连接mysql初识

package com.fmg.jdbc;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;

public class ConnectMySQL {
    public static void main(String[] args) {
        // 初始化UI
        Map<String, String> userInfo = init();
        // 校验登录
        Boolean isLoginSuccess = CheckLogin(userInfo);
        // 结果
        System.out.println(isLoginSuccess ? "登录成功" : "登录失败");
    }

    /**
     *
     * @param userInfo hashMap , 包含用户名, 密码
     * @return boolean true:登录成功 false: 登录失败
     */
    private static Boolean CheckLogin(Map<String, String> userInfo) {
        // 返回值
        boolean hasUser = false;
        // 读取配置信息
        ResourceBundle resourceBundle = ResourceBundle.getBundle("properties/db");
        String Driver = resourceBundle.getString("driver");
        String db = resourceBundle.getString("db");
        String dbUsername = resourceBundle.getString("username");
        String dbPassword = resourceBundle.getString("password");
        // 登录信息, 查表校验
        String username = userInfo.get("username");
        String password = userInfo.get("password");
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        String sql = "select * from t_user where username = '" + username + "' and password = '" + password + "'";
        try {
            Class.forName(Driver);
            conn = DriverManager.getConnection(db, dbUsername, dbPassword);
            stat =  conn.createStatement();
            rs = stat.executeQuery(sql);
            if(rs.next()){
                hasUser = true;
            }
            return hasUser;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     *  利用Scanner对象获取用户的用户名和密码
     * @return 用户输入的用户名和密码
     */
    private static Map<String, String> init() {
        Scanner s = new Scanner(System.in);
        System.out.print("请收入用户名:");
        String username = s.nextLine();
        System.out.print("请输入密码");
        String password = s.nextLine();
        Map<String, String> userInfo = new HashMap();
        userInfo.put("username", username);
        userInfo.put("password", password);
        return userInfo;
    }
}

 

上一篇:设计模式之美--单一职责原则


下一篇:2021-06-16 Redis基础数据类型