JDBC 工具类 及其 工具类使用

package com.hspedu.jdbc;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author: guorui fu
 * @versiion: 1.0
 */
public class JDBCUtils {
    private static String user;
    private static String password;
    private static String url;
    private static String driver;

    static{
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\mysql.properties"));
        } catch (IOException e) {
            //转换成运行异常,调用者可以捕获这个异常,或默认处理
            throw new RuntimeException(e);
        }
        user = properties.getProperty("user");
        password = properties.getProperty("password");
        url = properties.getProperty("url");
        driver = properties.getProperty("driver");
    }

    public static Connection getConnection(){

        try {
            return DriverManager.getConnection(url,user,password);
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables);
        }
    }

    public static void close(ResultSet resultSet, Connection connection, Statement statement){
        try {
            if (resultSet != null){
                resultSet.close();
            }
            if (connection != null){
                connection.close();
            }
            if (statement != null){
                statement.close();
            }
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables);
        }
    }
}

package com.hspedu.jdbc;

import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author: guorui fu
 * @versiion: 1.0
 */
public class JDBCUtils_use {
    @Test
    public void util_test(){
        //在try-catch外声明,方便关闭调用
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        //sql语句
        String sql = "delete from actor where `name` = '刘德华'";

        try {
            //建立连接
            connection = JDBCUtils.getConnection();
            //预处理
            preparedStatement = connection.prepareStatement(sql);
            //执行
            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables);
        } finally {
            //关闭资源
            JDBCUtils.close(null,connection,preparedStatement);
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值