栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JDBC封装工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JDBC封装工具类

JDBC封装为工具类

1.在src/main/resource下创建mysql.properties配置文件
2.加载配置文件
3.加载驱动 Class.forName(driver);
4.创建连接对象 

Connection conn = DriverManager.getConnection(url, user, password)

5.创建Statement语句
6.创建SQL语句
7.返回结果集
8.释放资源

mysql.properties:

driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/test?characterEncoding=utf8
user = root
password = 123456

JdbcUtils

package com.suyan.Utils;

import java.sql.*;
import java.util.Properties;


public class JdbcUtils {
    private static String driver = null ;
    private static String url = null ;
    private static String user = null ;
    private static String password = null ;

    //提供静态代码块:随着类的加载而加载
    static {
        //通过Properties对象获取配置文件的信息
        Properties properties = new Properties();
        //当配置文件放在src/main/resources的目录下时,只能使用Class.getResourceAsStream()方法来加载
        try {
            properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("mysql.properties"));
            driver = properties.getProperty("driver");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            url = properties.getProperty("url");
            //注册驱动
            Class.forName(driver);//建议写上
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //获取连接对象
    public static Connection getConnection() {
        try {
            Connection connection = DriverManager.getConnection(url, user, password);
            System.out.println("数据库连接成功~");
            return connection;
        } catch (SQLException e) {
            System.out.println("数据库连接失败~");
           throw new RuntimeException(e);
        }
    }

    //设置自动提交
    public static void setAutoCommit(Connection conn, boolean flag){
        try{
            if(flag == false){
                conn.setAutoCommit(false);
            }
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    //预处理SQL语句
    public static PreparedStatement prepareStatement(Connection conn, String sql){
        try{
            PreparedStatement ps = conn.prepareStatement(sql);
            return ps;
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    //查询处理集的next()方法
    public static boolean next(ResultSet rs){
        try{
            boolean flag = rs.next();
            return flag;
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    //释放资源
    public static void close(Connection conn, Statement...statement){
        //关于多条SQL语句,使用可变长形参列表来对其进行关闭
        for(int i=0;i
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/929787.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号