一、基本使用
- 导入jar包,在pom.xml中添加相关的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
- 定义配置文件,properties形式,放在resource文件夹里
druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/schema1
username=root
password=2010abc123kl
#初始化连接数
initialSize=5
#最大连接数
maxActive=10
#最长等待时间
maxWait=3000
- 获取数据库连接池对象,通过工厂类DuridDataSourceFactory来获取
public class DruidDemo {
public static void main(String[] args) throws Exception {
//1 定义配置文件
//2 加载配置文件
Properties properties=new Properties();
InputStream inputStream=DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(inputStream);
//3 获取连接池对象
DataSource ds=DruidDataSourceFactory.createDataSource(properties);
//4 获取连接
Connection conn=ds.getConnection();
System.out.println(conn);
}
}
- 遇到空指针异常(NullPointerException)的情况,可能是因为放在了src根目录下,maven项目要把配置文件放在resources文件夹
5.可正确返回结果
二、druid工具类的创建
public class JDBCUtils {
//1 定义成员变量
private static DataSource ds;
//2对datasource初始化赋值
static {
//3 加载配置文件
Properties pro=new Properties();
try {
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//4 获取datasource并且赋值
ds= DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @description:提供连接方法
*/
public static Connection getConnection() throws Exception{
return ds.getConnection();
}
/**
* @description:释放资源
*/
public static void close(Statement stmt,Connection conn){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs,Statement stmt, Connection conn){
if(rs!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* @description:获取连接池的方法
*/
public static DataSource getDataSource(){
return ds;
}
}
测试(以向数据表中插入一行数据为例)
public class DruidJDBCTest {
public static void main(String[] args) {
/**
* @description:添加操作给account
*/
Connection conn=null;
PreparedStatement pstmt=null;
try {
//1获取连接
conn=JDBCUtils.getConnection();
//2定义sql
String sql="insert into account values(?,?,?)";
//3获取pstmt对象
pstmt=conn.prepareStatement(sql);
//4给?赋值并执行sql
pstmt.setInt(1, 5);
pstmt.setString(2, "lin");
pstmt.setDouble(3, 2000);
int count=pstmt.executeUpdate();
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}finally {
//5释放资源
JDBCUtils.close(pstmt, conn);//放回池子里
}
}
}