javawebc3p0连接数据库
时间: 2023-12-16 19:04:44 浏览: 27
使用C3P0连接数据库是Java Web开发中常用的一种方式,具体步骤如下:
1.在项目中引入C3P0依赖,可以在Maven中添加以下依赖:
```xml
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
```
2.在项目的配置文件中添加数据库连接信息,例如在`application.properties`文件中添加以下配置:
```properties
# 数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=root
# C3P0连接池配置
c3p0.acquireIncrement=5
c3p0.initialPoolSize=10
c3p0.minPoolSize=5
c3p0.maxPoolSize=20
c3p0.maxIdleTime=120
```
3.在Java代码中使用C3P0连接数据库,例如:
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Demo {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 从连接池中获取连接
conn = dataSource.getConnection();
String sql = "SELECT * FROM user WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```