JDBC查询

回顾:
封装:临时存放我们查询出来的记录
集合:存放所有的记录对象,取出所有的查询出来的记录

封装用来生成实体类。集合用来存放实体类。
单元测试,导入依赖junit4
JDBC增加、删除、修改

1、JDBC查询
        查询                               增加、删除、修改
    加载驱动                                   加载驱动                     Class.forName()          Class.forName()
    创建连接                                    创建连接                     Connection                  Connection
创建SQL执行对象                 创建SQL执行对象              Statement                    Statement
执行SQL,有结果集              执行SQL,无结果集          ResultSet                     无
通过实体类存入集合                     释放资源                     List 实体类                   close()
    释放资源                                                                   close()


2、抽取工具类
加载驱动、创建连接;
释放资源;
(1)创建配置文件
resources—>jdbc.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db02
username=root
password=Root123456
(2)编写工具类
(2-1)读取配置文件,加载驱动
static{
    //1-2-1、将配置文件,转换为输入流
    InputStream inputStream=JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
    //1-2-2、通过属性对象(Properties),关联输入流
    Properties properties=new Properties();
    try {
        properties.load(inputStream);
        //1-2-3、通过属性的名字,取属性值
        driver=properties.getProperty("driver");
        url=properties.getProperty("url");
        username=properties.getProperty("username");
        password=properties.getProperty("password");
        //加载驱动
        Class.forName(driver);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            //释放资源
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

(2-2)编写获取连接方法
public static Connection getConnection(){
    Connection connection= null;
    try {
        connection = DriverManager.getConnection(url,username,password);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return connection;
}

(2-3)编写释放资源方法
public static void closeAll(ResultSet resultSet, Statement statement, Connection connection){
    try {
        if(resultSet!=null){
            resultSet.close();
        }
        if(statement!=null){
            statement.close();
        }
        if(connection!=null){
            connection.close();
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}


3、工具类的使用
工具类为我们解决了二个问题:(1)获取连接 (2)释放资源


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值