定义工具类
1. 定义一个类 JDBCUtils
2. 提供静态代码块加载配置文件,初始化连接池对象
3. 提供方法
1. 获取连接方法:通过数据库连接池获取连接
2. 释放资源
3. 获取连接池的方法
代码实现
配置文件
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/study username=root password=wzl2001323 initialSize=5 maxActive=10 maxWait=3000
工具类代码
package Druid.Jdbc; //jdbc工具类 import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JDBCUtils { //定义成员变量DataSource(连接池对象) private static DataSource ds; //在静态代码块中加载配置文件并获取连接池对象 static { //1.加载配置文件 Properties pro= new Properties(); try { pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); //2.获取Druid连接池对象 ds= DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } //方法 //1.获取链接对象 public static Connection getConnection() throws SQLException { return ds.getConnection(); } //2.释放资源 //2.1没有使用ResultSet public static void close(Statement stmt,Connection conn){ //调用该方法的重载方法关闭 close(null,stmt,conn); } public static void close(ResultSet rs,Statement stmt,Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } if (stmt != null) { try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } if(conn!=null) { try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } //3.获取连接池的方法 public static DataSource getDataSource(){ return ds; } }
测试
package Druid.Jdbc; import java.sql.*; public class Test01 { public static void main(String[] args) { Connection conn=null; PreparedStatement stmt=null; ResultSet rs=null; try { conn=JDBCUtils.getConnection(); String sql="select ename,sal from emp where ename like ?"; stmt=conn.prepareStatement(sql); stmt.setString(1,"A%"); rs=stmt.executeQuery(); while(rs.next()){ String ename=rs.getString("ename"); double sal=rs.getDouble("sal"); System.out.println(ename+","+sal); } } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtils.close(rs,stmt,conn); } } }