package com.yzhangm.druid;
import com.alibaba.druid.pool.DruidDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DBUtils {
private static DruidDataSource dataSource = new DruidDataSource();
static {
dataSource.setUrl("jdbc:mysql://localhost:3306/task?serverTimezone=UTC&useSSL=true");
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); //这个可以缺省的,会根据url自动识别
dataSource.setUsername("root");
dataSource.setPassword("123456");
//下面都是可选的配置
dataSource.setInitialSize(10); //初始连接数,默认0
dataSource.setMaxActive(30); //最大连接数,默认8
dataSource.setMinIdle(10); //最小闲置数
dataSource.setMaxWait(2000); //获取连接的最大等待时间,单位毫秒
dataSource.setPoolPreparedStatements(true); //缓存PreparedStatement,默认false
dataSource.setMaxOpenPreparedStatements(20); //缓存PreparedStatement的最大数量,默认-1(不缓存)。大于0时会自动开启缓存PreparedStatement,所以可以省略上一句代码
}
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;//出现错误 return null
}
}
。
package com.yzhangm.druid;
import Ajdbc1.DBUtil;
import Ajdbc1.Student;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void test() throws SQLException {
Connection connection = DBUtils.getConnection();
Student stu = new Student();
Statement stm = connection.createStatement();
String sql = "select * from student where id=7";
ResultSet rs = stm.executeQuery(sql);
if (rs.next()) {
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
}
System.out.println(stu.toString());
connection.close();
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < 100; i++) {
test();
}
}
}
/