配置文件连接数据库
数据库连接池:
保存数据库连接对象的容器相当于一个list
连接数据库
初始化连接数(初始化时创建多少个Connection对象)
最大连接数(连接池最多放几个连接对象)
最小连接数
最大空闲时间(连接对象后长时间未使用自动收回)
最大等待时间(连接池资源都被使用连接失败)
连接池使用javax.sql.DataSource接口
DataSource和jdbc一样只提供接口,由第三方实现
常见连接池
DBCP
Druid
C3P0
package Util;
import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.*;
public class JDBCUtil {
public static String username = "root";
public static String password = "123456";
//URL数据库地址
public static String URL="jdbc:mysql://localhost:3306/db0905?rewriteBatchedStatements=true";
//驱动地址
public static String driver="com.mysql.jdbc.Driver";
public static BasicDataSource ds=null;
//静态代码块,初始化时执行,且只执行一次
static {
//驱动只需加载一次
//创建连接池
ds = new BasicDataSource();
ds.setDriverClassName(driver);
ds.setUsername(username);
ds.setPassword(password);
ds.setUrl(URL);
}
public static Connection getConnection(){
try {
//连接数据库
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void close(Connection conn, PreparedStatement stmt, ResultSet rs){
if (rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package DataSource;
import Util.JDBCUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBCP {
public static void main(String[] args) {
String username = "root";
String password = "123456";
//URL数据库地址
String URL = "jdbc:mysql://localhost:3306/db0905";
//驱动地址
String driver = "com.mysql.jdbc.Driver";
//获取连接对象
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
try {
conn = JDBCUtil.getConnection();
String s = "select *from book";
stmt = conn.prepareStatement(s);
rs = stmt.executeQuery();
while (rs.next()){
String name = rs.getString("name");
String author = rs.getString("author");
System.out.println(name+"\t"+author);
}
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtil.close(conn,stmt,rs);
}
}