首页 > 其他分享 >jdbc简单封装

jdbc简单封装

时间:2022-12-28 17:25:15浏览次数:42  
标签:jdbc 封装 RuntimeException 简单 try connection sql catch new

构成:

  1、资源文件db.properties,中存放了驱动类地址、数据库url、用户名、密码。

  2、jdbc工具类JdbcUtils.java。

jdbc工具类中实现了:

  1、获取数据库连接。

  2、获取sql命令对象,包括Statement和PreparedStatement对象。

  3、执行DML语句。

  4、释放资源。

资源:

Oracle驱动地址:oracle.jdbc.driver.OracleDriver
Oracle的url:jdbc:oracle:thin:@localhost:1521:orcl

MySQL驱动地址:com.mysql.jdbc.Driver
MySQL的url:"jdbc:mysql://localhost:3306/leaningjdbc?useSSL=false"

代码:

  1、资源文件:

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/leaningjdbc?useSSL=false 
user=root 
pwd=123456

  2、JdbcUtils.java

package lurenjia.jdbcutils;

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

/**
 * 数据库连接工具类
 * @author lurenjia
 * @date 2022/12/28-16:02
 */
public class JdbcUtils {
    private static String driver;
    private static String url;
    private static String user;
    private static String pwd;
    //1.加载配置文件。2.完成数据库驱动的加载。
    static {
        //1.加载资源文件对象
        Properties pros = new Properties();
        //2.加载src目录下的资源文件
        try {
            pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //3.通过键名,获取值
        driver = pros.getProperty("driver");
        url = pros.getProperty("url");
        user = pros.getProperty("user");
        pwd = pros.getProperty("pwd");
        //4.加载数据库驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private JdbcUtils(){}

    /**
     * 获取数据库连接
     */
    public static Connection getConnection(){
        Connection connection=null;
        try {
            connection = DriverManager.getConnection(url,user,pwd);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    /**
     * 获取Statement对象
     * @param connection 数据库连接
     * @return 获取到的Statement对象
     */
    public static Statement getStatement(Connection connection){
        try {
            return connection.createStatement();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取PreparedStatement对象
     * @param connection 数据库连接
     * @param sql 预编译sql语句
     * @return 获取到的PreparedStatement对象
     */
    public static PreparedStatement getPreparedStatement(Connection connection,String sql){
        try {
            return connection.prepareStatement(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 关闭资源。
     * @param statement sql命令对象
     * @param connection 数据库连接对象
     */
    public static void close(Statement statement,Connection connection){
        try {
            if(statement!=null) {
                statement.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if(connection!=null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 关闭资源。
     * @param resultSet 结果集对象
     * @param statement sql命令对象
     * @param connection 数据库连接对象
     */
    public static void close(ResultSet resultSet,Statement statement,Connection connection){
        try {
            if(resultSet!=null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        close(statement,connection);
    }

    /**
     * 使用PreparedStatement执行DML语句,获取更新的数据数量。
     * @param sql sql语句
     * @param objects 参数
     * @return 更改数据的行数,若失败则返回-1
     */
    public static int executeDML(String sql,Object...objects){
        //结果中修改的数据行数
        int count = -1;

        //获取连接
        Connection connection = getConnection();
        try {
            //设置为手动提交
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //获取sql命令对象
        PreparedStatement preparedStatement = getPreparedStatement(connection,sql);
        //设置参数
        for(int i =0;i< objects.length;i++){
            try {
                preparedStatement.setObject(i+1,objects[i]);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        //执行
        try {
            count = preparedStatement.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            try {
                //发生错误时进行回滚
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
        //关闭资源
        close(preparedStatement,connection);
        return count;
    }
}

 

标签:jdbc,封装,RuntimeException,简单,try,connection,sql,catch,new
From: https://www.cnblogs.com/lurenjia-bky/p/17010806.html

相关文章

  • pinia的简单使用
    //安装//yarnaddpinia//在main.js中import{createPinia}from'pinia'constpinia=createPinia()app.use(pinia)//创建src/store/index.jsimport{d......
  • vue3封装axios并使用拦截器处理错误
    utils/http.jsimportaxiosfrom"axios";consthttp=axios.create({withCredentials:false,timeout:30000,baseURL:"http://127.0.0.1:8000",header......
  • 【详细】MySQL数据库与JDBC编程
    内容较多,建议收藏后慢慢看!●★●★●★●★●★●★●★●★●★●★●★●★●★●★●★●★●★●★●★●★●★●★●★●★MySQL数据库与JDBC编程 JDBC(JavaData......
  • vue3使用bootstrap的简单加载遮罩层
    之前有使用过bootstrap做过一个简单的加载遮罩层,现把它加入到vue中。加载遮罩层一般来讲整个app共用一个就可以,因此放到App.vue中,为不影响其它的业务逻辑,放到</template>......
  • Chronicle Pro - 一款简单 Mac 理财规划师,管理你的的个人预算
    使用Chronicle追踪和支付账单,管理你的个人预算,这是一款简单的Mac理财规划师。获得通知,这样你就不会错过下一个付款截止日期;你再也不用付滞纳金了。把你所有的账单放在一......
  • 消息提示封装elementui
    Vue.prototype.$msgTip = function (msg, temp,warningTime = 3000) {                let type = '';                switch......
  • 实现app短信验证码功能这样做就很简单!
    现在大多数app短信验证码服务都是由第三方服务商提供的,企业不需要对接运营商就可以让app具备三网发送短信功能,现在app短信验证码使用场景很多,比如说注册、登陆、支付等场景,a......
  • IntellIJ开发简单Minecraft插件(利用paper API)
    有的时候想实现服务器里的一些简单的功能,但是网上又找不到,这个时候可以尝试写一个出来。例如,在游戏里想要实现这样一个功能,玩家噶了之后在聊天栏处显示死亡坐标,这样可以方......
  • C#的λ表达式树(LambdaExpression)保姆级超详细简单入门教程
    有看过我之前发表过的C#相关文章分享和阅读过我代码的朋友们可能会在我的代码里面经常看到各种各样的λ表达式动态拼接,C#的λ表达式树是一个好东西,也是别的语言学不来......
  • SpringBoot高级篇搜索之Solr环境搭建与简单测试
    搜索可以说是非常常见的场景了,一般选择比较多的有solr和es,底层都是基于Lucene搜索引擎实现。之前简单的使用过solr,一直没有成体系的学习过,正好需要给一个内部项目封装统一的......