druidconfig使用实例
时间: 2023-10-24 18:22:28 浏览: 59
以下是使用DruidConfig的实例:
1. 初始化DruidConfig配置对象
```java
DruidConfig config = new DruidConfig();
config.setUrl("jdbc:mysql://localhost/testdb");
config.setUsername("testuser");
config.setPassword("testpass");
config.setDriverClassName("com.mysql.jdbc.Driver");
config.setInitialSize(5);
config.setMaxActive(10);
config.setMaxWait(10000);
config.setValidationQuery("SELECT 1");
```
2. 创建Druid数据源对象
```java
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(config.getUrl());
dataSource.setUsername(config.getUsername());
dataSource.setPassword(config.getPassword());
dataSource.setDriverClassName(config.getDriverClassName());
dataSource.setInitialSize(config.getInitialSize());
dataSource.setMaxActive(config.getMaxActive());
dataSource.setMaxWait(config.getMaxWait());
dataSource.setValidationQuery(config.getValidationQuery());
```
3. 获取数据库连接对象
```java
Connection conn = dataSource.getConnection();
```
4. 使用连接对象进行数据库操作
```java
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 1);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("username"));
}
```
阅读全文