8.druid连接池
一、连接参数的配置,为了程序方便修改采用database.properties文件的方式。
#连接的配置 driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/videomanager username=root password=123 #<!-- 初始传输连接数 --> initialSize=30 #最大连接数 maxActive=50 #<!-- 最小空闲连接数 --> minIdle=5 #<!-- 如果超出最大连接数开始等待毫秒数,可能因为这个设置会报错 --> maxWait=5000
二、通过database.properties创建DruidUtil连接池
package com.cqkj.utils; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; public class DruidUtil { static DataSource dataSource = null; static Connection con = null; static PreparedStatement pst = null; static ResultSet rs = null; static{ //实例化配置对象 Properties properties = new Properties(); try { //创建InputStream流 InputStream in = DruidUtil.class.getClassLoader().getResourceAsStream("database.properties"); //加载配置文件内容 properties.load(in); dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } //加载驱动、获取链接 public static Connection getConnection() { try { con = dataSource.getConnection(); } catch (Exception e) { e.printStackTrace(); } return con; } //执行查询sql public static ResultSet query(String sql,Object[] obj) { try { con = getConnection(); pst = con.prepareStatement(sql); if(obj != null) { for (int i = 0; i < obj.length; i++) { pst.setObject(i+1, obj[i]); } } rs = pst.executeQuery(); } catch (Exception e) { e.printStackTrace(); } return rs; } //执行增删改sql public static int update(String sql,Object[] obj) { int num = 0; try { con = getConnection(); pst = con.prepareStatement(sql); if(obj != null) { for (int i = 0; i < obj.length; i++) { pst.setObject(i+1, obj[i]); } } num = pst.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } return num; } public static void main(String[] args) { try { String sql = "select * from user"; Object[] obj = {}; rs = query(sql,obj); while(rs.next()) { String name = rs.getString(3); System.out.println(name); } } catch (SQLException e) { e.printStackTrace(); } } }