Druid 使用

2021-01-19

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>constxiong</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>druid-datasource-pool</artifactId>

    <dependencies>
        <!-- druid 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.4</version>
        </dependency>
        <!-- MySQL 8.0.21 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
    </dependencies>

    <build>

    </build>
</project>

 

java 代码

package constxiong;

import com.alibaba.druid.pool.DruidDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 测试 druid 数据库连接池
 */
public class Test {

    public static void main(String[] args) throws Exception {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/constxiong?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8");
        ds.setUsername("root");
        ds.setPassword("constxiong@123");
        try (Connection connection = ds.getConnection(); Statement statement = connection.createStatement()){
             statement.execute("select * from user");
             try(ResultSet resultSet = statement.getResultSet()){
                 while (resultSet.next()) {
                     Integer id = resultSet.getInt(1);
                     String name = resultSet.getString(2);
                     System.out.println(id + "-" + name);
                 }
             }
        }
        ds.close();
    }
}

 

打印结果

ConstXiong 备案号:苏ICP备16009629号-3