zoukankan      html  css  js  c++  java
  • 自定义类库:简单的JDBC工具类

    一、工具类

    package com.moy.whymoy.project.helper;
    
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.Properties;
    
    /**
     * Description:jdbc工具类<br/>
     *
     * <pre></pre>
     *
     * Date:2017/9/15 <br/>
     * Email:moy25@foxmail.com <br/>
     *
     * @author YeXiangYang
     */
    public class DBClient {
    
        private String userName;// 用户名
        private String password;// 密码
        private String driverName;// 数据库驱动类
        private String url;// 数据库url
        private Connection conn;// 数据库连接
        private static final String DEFAULT_CONN_CONFIG = "/db.properties";// 默认数据库连接配置文件
    
        private DBClient() {
            super();
        }
    
        private DBClient(String driverName, String url, String userName, String password) {
            super();
            this.driverName = driverName;
            this.url = url;
            this.userName = userName;
            this.password = password;
        }
    
        /**
         * 创建数据库连接客户端,默认加载配置文件
         *
         * @return 数据库连接客户端
         */
        public static DBClient createDefaultClient() {
            DBClient client = new DBClient();
            client.initDefaultConfig();
            return client;
        }
    
        /**
         * 根据配置文件加载数据库连接客户端
         *
         * @param configNamePath
         *            配置文件
         * @return 数据库连接客户端
         */
        public static DBClient createClient(String configNamePath) {
            DBClient client = new DBClient();
            client.initConfig(configNamePath);
            return client;
        }
    
        /**
         * 根据数据库连接信息加载数据库连接客户端
         *
         * @param driverName
         *            数据库驱动类
         * @param url
         *            数据库url
         * @param userName
         *            用户名
         * @param password
         *            密码
         * @return 数据库连接客户端
         */
        public static DBClient createClient(String driverName, String url, String userName, String password) {
            return new DBClient(driverName, url, userName, password);
        }
    
        /**
         * 默认加载classpath:db.properties文件
         */
        private void initDefaultConfig() {
            initConfig(DEFAULT_CONN_CONFIG);
        }
    
        /**
         * 加载properties配置文件,设置数据库连接信息
         *
         * @param fileNamePath
         *            初始化配置文件
         */
        private void initConfig(String fileNamePath) {
            try {
                InputStream inputStream = getClass().getResourceAsStream(fileNamePath);
                Properties prop = new Properties();
                prop.load(inputStream);
                driverName = prop.getProperty("jdbc.driverName");
                url = prop.getProperty("jdbc.url");
                userName = prop.getProperty("jdbc.username");
                password = prop.getProperty("jdbc.password");
            } catch (Exception e) {
                throw new RuntimeException(String.format("读取数据库配置文件:[%s]失败!", fileNamePath), e);
            }
        }
    
        /**
         * 获取数据库连接
         *
         * @return 数据库连接
         */
        public Connection getConnection() {
            if (Objects.isNull(conn)) {
                conn = createConnection();
            }
            return conn;
        }
    
        /**
         * 创建数据库连接
         *
         * @return 数据库连接
         */
        public Connection createConnection() {
            try {
                Class.forName(driverName);
                return DriverManager.getConnection(url, userName, password);
            } catch (Exception e) {
                throw new RuntimeException("创建数据库连接错误!", e);
            }
        }
    
        /**
         * 执行修改语句
         *
         * @param sql
         *            sql语句
         * @param params
         *            参数
         * @return 返回影响了几条数据
         * @throws SQLException
         *             调用异常
         */
        public int executeUpdate(String sql, Object... params) throws SQLException {
    
            PreparedStatement statement = getPreparedStatement(sql, params);
    
            return statement.executeUpdate();
        }
    
        /**
         * 获取PreparedStatement
         *
         * @param sql
         *            sql语句
         * @param params
         *            参数
         * @return PreparedStatement
         * @throws SQLException
         *             调用异常
         */
        private PreparedStatement getPreparedStatement(String sql, Object... params) throws SQLException {
    
            Connection connection = getConnection();
    
            PreparedStatement statement = connection.prepareStatement(sql);
    
            setStatementParam(statement, params);
    
            return statement;
        }
    
        /**
         * 设置PreparedStatement占位符参数
         *
         * @param statement
         *            PreparedStatement
         * @param params
         *            参数
         * @throws SQLException
         *             调用异常
         */
        private void setStatementParam(PreparedStatement statement, Object... params) throws SQLException {
            if (Objects.nonNull(statement) && Objects.nonNull(params)) {
                for (int i = 0; i < params.length; i++) {
                    statement.setObject(i + 1, params[i]);
                }
            }
        }
    
        /**
         * 执行查询语句
         *
         * @param sql
         *            sql语句
         * @param params
         *            参数
         * @return ResultSet结果集
         * @throws SQLException
         *             调用异常
         */
        public ResultSet query(String sql, Object... params) throws SQLException {
    
            PreparedStatement statement = getPreparedStatement(sql, params);
    
            return statement.executeQuery();
        }
    
        /**
         * 执行查询语句,组装查询结果
         *
         * @param sql
         *            sql语句
         * @param params
         *            参数
         * @return 返回List<Map<String, Object>>数据结构
         * @throws SQLException
         *             调用异常
         */
        public List<Map<String, Object>> queryAsMap(String sql, Object... params) throws SQLException {
    
            ResultSet resultSet = query(sql, params);
    
            return rebuildResultSet(resultSet);
        }
    
        /**
         * 组装ResultSet成List<Map<String, Object>>数据结构
         *
         * @param resultSet
         *            原始查询结果
         * @return 返回List<Map<String, Object>>数据结构
         * @throws SQLException
         *             调用异常
         */
        private List<Map<String, Object>> rebuildResultSet(ResultSet resultSet) throws SQLException {
            if (Objects.isNull(resultSet)) {
                return new ArrayList<Map<String, Object>>();
            }
            List<Map<String, Object>> result = new ArrayList<>(resultSet.getRow());
    
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
    
            while (resultSet.next()) {
                Map<String, Object> map = new HashMap<>((int) (columnCount / 0.75));
                for (int i = 0; i < columnCount; i++) {
                    String columnName = metaData.getColumnName(i + 1);
                    Object columnValue = resultSet.getObject(columnName);
                    map.put(columnName.toUpperCase(), columnValue);
                }
                result.add(map);
            }
            return result;
        }
    
        /**
         * 释放资源
         *
         * @throws SQLException
         *             调用异常
         */
        public void release() throws SQLException {
            if (Objects.nonNull(conn) && !conn.isClosed()) {
                conn.close();
            }
        }
    }

    二、默认配置

    jdbc.driverName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/spring
    jdbc.username=root
    jdbc.password=123
    默认配置文件

    三、测试

    package com.moy.whymoy.project.helper;
    
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.sql.SQLException;
    
    /**
     * Project:web  <br/>
     * Description:  <br/>
     * Date:2017/12/12  <br/>
     * Email:moy25@foxmail.com  <br/>
     *
     * @author YeXiangYang
     */
    public class DBClientTest {
    
        public DBClient[] clients = new DBClient[3];
    
        @Before
        public void before() {
            clients[0] = DBClient.createDefaultClient();
            clients[1] = DBClient.createClient("/db.properties");
            clients[2] = DBClient.createClient("com.mysql.jdbc.Driver",
                    "jdbc:mysql://localhost:3306/spring", "root", "123");
        }
    
        @After
        public void after() throws SQLException {
            for (DBClient client : clients) {
                client.release();
            }
        }
    
    
        @Test
        public void getConnection() throws Exception {
            for (DBClient client : clients) {
                System.out.println(client.getConnection());
            }
        }
    
        @Test
        public void createConnection() throws Exception {
            for (DBClient client : clients) {
                System.out.println(client.createConnection());
            }
        }
    
        @Test
        public void executeUpdate() throws Exception {
            String updateSqlWithParam = "update new_inf set name=? where id=?";
            for (int i = 0, len = clients.length; i < len; i++) {
                System.out.println(clients[i].executeUpdate(updateSqlWithParam, new Object[]{i + 1, i + 1}));
            }
        }
    
        @Test
        public void query() throws Exception {
            String sql = "select * from new_inf";
            for (DBClient client : clients) {
                System.out.println(client.query(sql));
            }
            String sqlWithParam = "select * from new_inf where id = ?";
            for (int i = 0, len = clients.length; i < len; i++) {
                System.out.println(clients[i].query(sqlWithParam, new Object[]{i + 1}));
            }
        }
    
        @Test
        public void queryAsMap() throws Exception {
            String sql = "select * from new_inf";
            for (DBClient client : clients) {
                System.out.println(client.queryAsMap(sql));
            }
            String sqlWithParam = "select * from new_inf where id = ?";
            for (int i = 0, len = clients.length; i < len; i++) {
                System.out.println(clients[i].queryAsMap(sqlWithParam, new Object[]{i + 1}));
            }
        }
    
    }
    测试

    yexiangyang

    moyyexy@gmail.com


     

  • 相关阅读:
    运行top时,会报unknown terminal type错误
    CSS 学习笔记
    HTML学习笔记
    在window平台搭建Qt开发环境(使用VS2008 IDE)
    GNU的ar,ranlib和nm
    GifCam
    linux modprobe命令参数及用法详解--linux加载模块命令
    如何制作gif动画,丰富自己的博客?
    来自 Github 的图形化 Git 使用教程
    idea创建maven-archetype-webapp项目无java目录
  • 原文地址:https://www.cnblogs.com/moy25/p/8027832.html
Copyright © 2011-2022 走看看