Druid使用实例

当然,以下是一个详细的Druid示例代码,演示了如何配置和使用Druid连接池:

import com.alibaba.druid.pool.DruidDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DruidDemo {
    public static void main(String[] args) {
        // 创建Druid数据源
        DruidDataSource dataSource = new DruidDataSource();

        // 配置数据源属性
        dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase");
        dataSource.setUsername("username");
        dataSource.setPassword("password");

        // 配置连接池属性
        dataSource.setInitialSize(5);
        dataSource.setMaxActive(10);
        dataSource.setMinIdle(3);
        dataSource.setMaxWait(3000);

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            // 从连接池获取连接
            connection = dataSource.getConnection();

            // 执行查询
            String sql = "SELECT * FROM students";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();

            // 处理查询结果
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            // 释放资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }

            // 关闭数据源
            dataSource.close();
        }
    }
}

在上述代码中,我们首先创建了一个DruidDataSource对象,然后配置了数据库连接信息和连接池属性。接下来,我们通过调用getConnection()方法从连接池中获取一个连接对象。然后,我们执行一个查询操作,将结果打印出来。最后,我们释放资源,包括关闭结果集、预处理语句和连接对象,以及关闭数据源。

需要注意的是,在实际使用中,我们通常会将数据源的配置信息放在外部配置文件中,例如druid.properties,并使用Properties对象加载配置。然后,可以通过调用dataSource.configFromPropety(props)方法将属性配置应用到数据源中。

此外,为了正确使用Druid连接池,您还需要将Druid的依赖项添加到项目的构建文件(例如pom.xml)中。例如,在Maven项目中,您可以添加以下依赖项:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
</dependency>

请确保使用正确的Druid版本号,根据您的项目需求进行调整。

posted @ 2023-05-30 17:39  田野与天  阅读(162)  评论(0编辑  收藏  举报