首页 > 其他分享 >JDBC 工具类

JDBC 工具类

时间:2023-07-26 11:37:28浏览次数:30  
标签:JDBC args param connection preparedStatement sql 工具 null

工具类JDBCUtils包括以下方法

 

项目结构如下

 

代码如下

package com.lyl.utils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


// 可以将CRUD操作设计为静态方法
// 也可以写成DAO类,让实体类继承CRUD的方法
public class JDBCUtils {
    /**
     * 获取数据库的一个连接
     * 方法中使用JDBCUtils.class.getClassLoader().getResourceAsStream(path),该path是指类路径classPath,
     * 即在普通项目中指"src/",在web项目中指"/WEB-INF/classes/"
     *
     * @param propertiesPath 返回配置文件的路径propertiesPath,该文件存放连接数据库需要的user、password、url、driverClass等相关参数
     * @return 到数据库的连接
     * @throws IOException
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public static Connection getConnection(String propertiesPath) throws Exception{
        InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream(propertiesPath);
        Properties properties = new Properties();
        properties.load(resourceAsStream);

        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driverClass = properties.getProperty("driverClass");


        Class.forName(driverClass);
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;

    }

    /**
     * 对于增删改操作,关闭到数据库的connection和statement
     * @param conn 到数据库的连接 conn
     * @param ps sql对应的statement ps
     */
    public static void closeResource(Connection conn, Statement ps) {
        try {
            // 避免空指针(对象没有创建的时候就关闭)
            if (conn != null)
                conn.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            // 避免空指针(对象没有创建的时候就关闭)
            if (ps != null)
                ps.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 对于查找操作,关闭到数据库的connection、statement和resultSet
     * @param conn 到数据库的连接 conn
     * @param ps sql对应的statement ps
     * @param rs 查询出的结果集 rs
     */
    public static void closeResource(Connection conn, Statement ps, ResultSet rs) {
        try {
            // 避免空指针(对象没有创建的时候就关闭)
            if (conn != null)
                conn.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            // 避免空指针(对象没有创建的时候就关闭)
            if (ps != null)
                ps.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            // 避免空指针(对象没有创建的时候就关闭)
            if (rs != null) {
                rs.close();

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    /**
     * 输入带占位符的sql和填补占位符的参数,执行增删改操作
     * @param sql 带占位符的sql
     * @param args 填补占位符的参数 args
     * @return 成功操作的行数,出错则返回-1
     * @throws SQLException
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static int update(String sql, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        int ans = -1;
        try {
            connection = JDBCUtils.getConnection("login.properties");
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            ans = preparedStatement.executeUpdate();
            return ans;
        }  catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.closeResource(connection, preparedStatement);

        }
        return -1;

    }

    /**
     * 输入实体类的Class对象,带占位符的sql,填补占位符的参数,执行查询操作,返回实体类的List集合
     * @param tClass 实体类的Class对象 tClass
     * @param sql 带占位符的sql
     * @param args 填补占位符的参数 args
     * @param <T> 指实体类的类型 <T>
     * @return 执行查询操作,返回实体类的List集合,出错则返回null
     */
    public static <T> List<T> queryToEntityClass(Class<T> tClass, String sql, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        ResultSet resultSet = null;
        List<T> ansList = null;
        try {
            connection = JDBCUtils.getConnection("login.properties");
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof Integer) {
                    preparedStatement.setInt(i + 1, (Integer) args[i]);
                } else if (args[i] instanceof String) {
                    preparedStatement.setString(i + 1,  (String) args[i]);
                } else {
                    preparedStatement.setObject(i + 1, args[i]);
                }

            }

            resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            ansList = new ArrayList<>();
            while (resultSet.next()) {
                // 创建一个实体类对象

                T entityClass = tClass.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    // 从ResultSet中获取属性值
                    Object fieldValue = resultSet.getObject(i + 1);
                    // 通过元数据MetaData获得属性名,通过反射获得实体类的属性
                    String columnName = metaData.getColumnName(i + 1);
                    Field field = entityClass.getClass().getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(entityClass, fieldValue);
                }
                ansList.add(entityClass);

            }
            return ansList;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }

        return null;
    }

}

 

标签:JDBC,args,param,connection,preparedStatement,sql,工具,null
From: https://www.cnblogs.com/lylhome/p/17581968.html

相关文章

  • 大规模敏捷框架管理工具(SAFe,SOS)
    ​什么是SAFe?SAFe(ScaledAgileFramework)是全球运用最广泛的大规模敏捷框架。SAFe融合了精益、敏捷和DevOps,它是一个知识库,囊括了大量已被证明的精益敏捷实践和能力。SAFe诞生于2011年,短短12时间,全球已经有超过120万SAFe认证专业人士,并且持续保持快速增长,得到了全球越来越多专人......
  • JDBC preparedStatement.executeQuery() 与 preparedStatement.executeQuery(sql)
    preparedStatement.executeQuery()这个方法是执行带占位符、已经预编译的sql命令而它--->preparedStatement.executeQuery(sql)这个方法是执行未预编译、完整的sql命令,而不是预编译的sql命令preparedStatement不是应该执行预编译的sql吗?是这样的,但是preparedStatement还兼......
  • Git工具推荐
    推荐软件FastGithub可以让你轻松访问github推荐网站github加速访问输入github网址,生成快速访问地址gitclone加速器输入要下载的github网址,生成替代下载网址推荐谷歌插件GitHub加速1.0.8参考此博客下载安装......
  • 解决高分屏下Matlab工具栏字体过小
    能够看到工具栏,说明你已经能够打开matlab了,不管你是以何种方式打开的。首先打开matlab,然后在命令行输入一下代码:#在命令行内输入如下命令,其中2.0是放大的尺度,根据需要自行设置s=settings;s.matlab.desktop.DisplayScaleFactor;s.matlab.desktop.DisplayScaleFactor.Persona......
  • 如何删除PPT中工具栏口袋动画
    口袋动画官网无法打开http://www.papocket.com/插件无法使用卸载在【程序和功能】中卸载后,打开PPT,菜单还是存在选项——加载项,点击以p开头的一串代码(com加载项),点击转到,选择两个以p开头的加载项,依次删除即可注意不要把其他的加载项删了......
  • TailWind CSS工具库使用
    一、简介官方文档本CSS框架本质上是一个工具集,包含了大量类似 flex、 pt-4、 text-center 以及 rotate-90 等工具类,可以组合使用并直接在HTML代码上实现任何UI设计。二、安装介绍VUE项目的相关安装步骤1.安装TailWindCSS通过npm安装tailwindcss和它的相关依......
  • 验证码工具tesserocr安装
    1.安装tesserocr必须先安装tesseract。  tesseract地址:https://digi.bib.uni-mannheim.de/tesseract/  可以选择最新版本  一直点击下一步下一步就可以了2.配置环境变量  1)将tesseract目录分别放到用户变量和系统变量中  2)将D:\ProgramFiles\Tesseract-O......
  • 如何让 Rust 不使用 Visual Studio 的工具链编译
    假如你不想使用VisualStudio进行开发,也不想电脑上多出几个G的累赘,也可以选择使用GNU进行编译,在此记录一下更换工具链的方法。安装后更改安装完成后,确保你的rustup命令可以正常使用。在控制台中执行rustupdefaultstable-x86_64-pc-windows-gnu命令,等待下载完成即可。安......
  • Tesseract开源的OCR工具及python pytesseract安装使用
    一、介绍Tesseract是一款由Google赞助的开源OCR。pytesseract是python包装器,它为可执行文件提供了pythonicAPI。Tesseract已经有30年历史,开始它是惠普实验室的一款专利软件,在2005年后由Google接手并进一步开发和完善。Tesseract支持多种语言文字的检测和识别,包括中文、英......
  • java~IDE工具技巧
    代码折叠操作:选中代码,按ctrl+alt+t,之后选择region代码环绕折叠后的效果spring代码格式化每个项目添加统一的依赖包<plugin><groupId>io.spring.javaformat</groupId><artifactId>spring-javaformat-maven-plugin</artifactId><version>0.0.35</version&g......