11.数据库工具类JDBCUtils

数据库工具类JDBCUtils

什么时候自己创建工具类?如果一个公共能经常要用到,建议将这个功能做成一个工具类,可以在不同的地方重用

补充 :通过.class类文件获取流或者ClassLoader类加载器获取当前src路径下的文件

...\src\pro.properties

url="jdbc:mysql:///jdbclearn"
user=root
password=abc123
driver=com.mysql.jdbc.Driver

Main

// 【推荐】1.在src下查找pro.properties配置文件直接作为输入流
InputStream in = Main.class.getClassLoader().getResourceAsStream("pro.properties");
Properties pro = new Properties();
pro.load(in);

// 2.获得src文件夹下对应文件的绝对路径 通过当前类获得ClassLoader!
ClassLoader classLoader = Main.class.getClassLoader();
URL source = classLoader.getResource("pro.properties");
String path = source.getPath();
Properties properties = new Properties();
properties.load(new FileReader(path));

1.创建类jdbcUtil包含3个方法

  1. 可以把几个字符串定义成常量
    • 用户名
    • 密码
    • URL
    • 驱动类
  2. 得到数据库的连接:getConnection()
  3. 关闭所有打开的资源
    • close(Connection conn,Statement stmt)
    • close(Connection conn,Statement stmt,ResultSet rs)

2.jdbcUtil工具类实现

import java.sql.*;

public class JdbcUtils {
    // 可以把几个字符串定义成常量:用户名,密码,URL,驱动类
    private static final String USER = "root";
    private static final String PWD = "abc123";
    private static final String URL = "jdbc:mysql://localhost:3306/jdbclearn";
    private static final String DRIVER = "com.mysql.jdbc.Driver";

    /**
     * 注册驱动(可以省略)
     */
    static {
        try {
            Class.forName(DRIVER); }
            catch (ClassNotFoundException e) { e.printStackTrace(); }
    }

    /**
     * 得到数据库的连接
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PWD);
    }

    /**
     * 关闭所有打开的资源
     */
    public static void close(Connection conn, Statement stmt){
        if(stmt != null) {
            try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
        }
        if(conn != null) {
            try { conn.close(); }catch (SQLException e) { e.printStackTrace(); }
        }

    }

    /**
     * 关闭所有打开的资源 重载
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        if(rs != null) {
            try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
        }

        close(conn, stmt);
    }
}

3.登录案例【未防范SQL注入风险;密码未进行加密】

1.数据库准备

create database if not exists jdbclearn;
use jdbclearn;

create table user (
    id int primary key auto_increment,
    name varchar(20),
    password varchar(20)
);

insert into user values
(null, 'jack', '123'),
(null, 'rose', '456');

2.使用上面的jdbcUtil工具类进行登录实验

  • Login类
import java.sql.*;
import java.util.Scanner;

public class Login {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入用户名>> ");
        String name = input.nextLine();
        System.out.println("请输入密码>> ");
        String password = input.nextLine();
        login(name, password);
    }

    public static void login(String name, String password) {
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            connection = JdbcUtils.getConnection();
            statement = connection.createStatement();
            String sql = "select * from user where name='" + name +"' and password='" + password + "'";
            System.out.println(sql);
            rs = statement.executeQuery(sql);
            if(rs.next()) {
                System.out.println("登录成功,欢迎您:" + name);
            } else {
                System.out.println("登录失败!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection, statement, rs);
        }
    }
}
  • 正常登录以及结果
请输入用户名>>
jack
请输入密码>>
123
select * from user where name='jack' and password='123'
登录成功,欢迎您:jack
  • SQL注入方式登录
请输入用户名>>
someONe
请输入密码>>
a' or '1' = '1
select * from user where name='someONe' and password='a' or '1' = '1'
登录成功,欢迎您:someONe

使用PreparedStatement//www.greatytc.com/p/8553fc6b9f41@接口可以防止SQL注入的风险

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • JDBC简介 SUN公司为了简化、统一对数据库的操作,定义了一套Java操作数据库的规范,称之为JDBC。JDBC...
    奋斗的老王阅读 1,550评论 0 51
  • 本文内容 1.什么是JDBC以及为什么要使用JDBC 2.JDBC核心API的讲解 3.使用JDBC核心API进行...
    Vincilovfang阅读 1,240评论 0 11
  • 蓝天欲梦,海棠依旧,望故归切。 何时柳堤携手,听聆鸟语,吟花追蝶。 恨不重山飞越,驾鸾音尘绝。 日夜盼、惆怅台阶,...
    刘小地阅读 664评论 28 77
  • 李笑来--通往财富的自由之路 昨晚发文写了李笑来老师的努力经历,今晚继续李笑来老师的更多的故事。 李老师正因为特别...
    我是岸阅读 609评论 2 7
  • 今年初辞职转型营销,对自己这个20年后线工作的人的确是一大挑战,离开了舒适区,完全靠业绩吃饭。现在出来第三个月,才...
    罗芳慧阅读 134评论 0 0