zoukankan      html  css  js  c++  java
  • 关于Druid 连接池的使用方法

    根据个人学习进度分享出来的Druid连接池的使用方法,欢迎指正。

    一、创建并修改 database.properties 文件如下

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/testjavadb?useSSL=false
    username=root
    password=root
    #初始化连接
    initialSize=10
    #最大连接数
    maxActive=50
    #最小空闲连接
    minIdle=5
    #超时等待时间
    maxWait=5000

    二、创建并修改DruidUntils 相关连接池属性及数据库操作方法

    public class DruidUntils {
        // 创建连接对象
        private static DruidDataSource dataSource;
        private static Connection connection;
        private static PreparedStatement pstmt = null;
        private static ResultSet resultSet = null;
        static {
            // 创建连接池
            Properties properties = new Properties();
            
            InputStream inputStream = DruidUntils.class.getClassLoader().getResourceAsStream("database.properties");
            
            try {
                properties.load(inputStream);
                System.out.println(properties);
                // 通过德鲁伊连接池工厂创建一个连接池,自动解析properties文件里的键值对
                dataSource =  (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
    
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    
        public static DruidDataSource getDataSource() {
            return dataSource;
        }
      // 初始化连接池
      
    public static Connection getConnection() { try { connection = dataSource.getConnection(); return connection; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * 查询返回单条记录,并保存在map中 * * @param sql * @param params * @return * @throws SQLException */ public static Map<String, Object> findSimpleResult(String sql, List<Object> params) throws SQLException { Map<String, Object> map = new HashMap<String, Object>(); int index = 1; pstmt = (PreparedStatement) connection.prepareStatement(sql); System.out.println(pstmt); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery();// 返回查询结果 // 获取此 ResultSet 对象的列的编号、类型和属性。 ResultSetMetaData metaData = resultSet.getMetaData(); int col_len = metaData.getColumnCount();// 获取列的长度 while (resultSet.next())// 获得列的名称 { for (int i = 0; i < col_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null)// 列的值没有时,设置列值为“” { cols_value = ""; } map.put(cols_name, cols_value); } } return map; } public static void closeAll() { try { if (resultSet != null) { resultSet.close(); } if (pstmt != null) { pstmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 完成对数据库的表的添加删除和修改的操作 * * @param sql * @param params * @return * @throws SQLException */ public boolean updateByPreparedStatement(String sql, List<Object> params) throws SQLException { boolean flag = false; int result = -1;// 表示当用户执行添加删除和修改的时候所影响数据库的行数 pstmt = connection.prepareStatement(sql); int index = 1; // 填充sql语句中的占位符 if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } result = pstmt.executeUpdate(); flag = result > 0 ? true : false; return flag; } /** * 查询返回多行记录,并保存在List<Map<String, Object>>中 * * @param sql * @param params * @return * @throws SQLException */ public List<Map<String, Object>> findMoreResult(String sql, List<Object> params) throws SQLException { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } map.put(cols_name, cols_value); } list.add(map); } return list; } /** * jdbc的封装可以用反射机制来封装:取得单条记录并保存在javaBean中(这里使用到了泛型) * * @param sql * @param params * @param cls * @return * @throws Exception */ public <T> T findSimpleRefResult(String sql, List<Object> params, Class<T> cls) throws Exception { T resultObject = null; int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { // 通过反射机制创建实例 resultObject = cls.newInstance(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } // 返回一个 Field 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明字段。 Field field = cls.getDeclaredField(cols_name); field.setAccessible(true);// 打开javabean的访问private权限 field.set(resultObject, cols_value);// 为resultObject对象的field的属性赋值 } } return resultObject; } /** * 通过反射机制访问数据库 jdbc的封装可以用反射机制来封装:取得多条记录并保存在javaBean的集合中中(这里使用到了泛型) * * @param <T> * @param sql * @param params * @param cls * @return * @throws Exception */ public <T> List<T> findMoreRefResult(String sql, List<Object> params, Class<T> cls) throws Exception { List<T> list = new ArrayList<T>(); int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { T resultObject = cls.newInstance(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } Field field = cls.getDeclaredField(cols_name); field.setAccessible(true); field.set(resultObject, cols_value); } list.add(resultObject); } return list; } /** * 将连接参数写入配置文件 * * @param url * jdbc连接域名 * @param user * 用户名 * @param password * 密码 */ public static void writeProperties(String url, String user, String password) { Properties pro = new Properties(); FileOutputStream fileOut = null; try { fileOut = new FileOutputStream("Config.ini"); pro.put("url", url); pro.put("user", user); pro.put("password", password); pro.store(fileOut, "My Config"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fileOut != null) fileOut.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 读取配置文件的连接参数 * * @return 返回list */ public static List readProperties() { List list = new ArrayList(); Properties pro = new Properties(); FileInputStream fileIn = null; try { fileIn = new FileInputStream("Config.ini"); pro.load(fileIn); list.add(pro.getProperty("url")); list.add(pro.getProperty("user")); list.add(pro.getProperty("password")); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fileIn != null) fileIn.close(); } catch (IOException e) { e.printStackTrace(); } } return list; } }

    三、创建外部使用文件

    public class UserDaoimpl {
        static Scanner sc = new Scanner(System.in);
        public static String sql = "select * from userlogin where username=? and password = ?";
        
        
        public static void main(String[] args) throws SQLException {
            // 初始化德鲁伊池
            DruidUntils.getConnection();
            
            System.out.println("账号:");
            String username = sc.next();
            System.out.println("密码:");
            String password = sc.next();
            ArrayList<Object> list = new ArrayList<Object>();
            list.add(username);
            list.add(password);
            
            Map<String, Object> simpleMap = DruidUntils.findSimpleResult(sql,list);
            for (java.util.Map.Entry<String, Object> entry : simpleMap.entrySet()) {
                    System.out.println(entry.getKey()+":"+ entry.getValue());
            }
            DruidUntils.closeAll();
        }
        
    }

    相关文件包:

    关于mysql-connector-java-5.1.45.jar包 资源下载

    关于druid-1.1.22.jar包 资源下载

  • 相关阅读:
    在ConcurrentModificationException异常上的联想
    记录一下自己爬虎牙LOL主播的爬虫思路
    ajax解决跨域问题
    解决多线程下数据库操作问题
    浅谈时间复杂度
    想一下,最大公约数怎么求
    IO流与IO缓冲
    循环移位
    3Sum探讨(Java)
    Two Sum(两个数的相加)
  • 原文地址:https://www.cnblogs.com/bomdeyada/p/13356530.html
Copyright © 2011-2022 走看看