前言
java连接数据库有许多的方法,在此先只讨论三种,分别是原生jdbc连接数据库,c3p0连接数据库,dbcp连接数据库
c3p0与dbcp区别:
- dbcp没有自动回收空闲连接的功能
-
c3p0有自动回收空闲连接功能
-
两者主要是对数据连接的处理不同c3p0提供最大空闲时间,dbcp提供最大连接数。前者是如果连接时间超过最大连接时间,就会断开当前连接。dbcp如果超过最大连接数,就会断开所有连接。
jdbc.properties配置文件形式,利用java原生jdbc连接数据库
当然如果不想使用properties配置文件形式可以直接使用参数。
添加依赖
第一个依赖是连接mysql必须的,后面的是slf4j及log4j日志所需的依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- log -->
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<!-- <scope>test</scope> -->
</dependency>
工具类PropertiesUtil和JDBCDBUtils
package util;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PropertiesUtil {
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
//private final Logger logger = LoggerFactory.getLogger(this.getClass());
private static Properties props;
//根据文件路径加载文件
public static void setProperties(String fileName){
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
} catch (IOException e) {
logger.error("配置文件读取异常",e);
}
}
public static Properties getProperties(){
return props ;
}
//自定义俩个get方法,方便调用工具类读取properties文件的属性
public static String getString(String key){
String value= props.getProperty(key.trim());
if (StringUtils.isBlank(value)){
return null;
}
return value.trim();
}
public static String getString(String key,String defaultValue){
String value= props.getProperty(key.trim());
if (StringUtils.isBlank(value)){
value = defaultValue;
}
return value.trim();
}
}
PropertiesUtil工具类用来读取properties文件的内容
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCDBUtils {
static{
PropertiesUtil.setProperties("mysql.properties");
}
// 数据库用户名
private static final String USERNAME = PropertiesUtil.getString("username");
// 数据库密码
private static final String PASSWORD = PropertiesUtil.getString("password");
// 数据库地址
private static final String URL = PropertiesUtil.getString("url");
private static Connection con;
public static Connection getConnect() throws SQLException{
try {
//jdbc现在可以不显示的加载驱动,自动加载
//Class.forName(PropertiesUtil.getString("driver"));
con= DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public static void close(Connection con,Statement state,ResultSet rs){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("result关闭失败");
}
finally {
rs=null;
}
try {
if(state!=null){
state.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("statement关闭失败");
}finally {
state=null;
}
try {
if(con!=null){
con.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Connect关闭失败");
}finally {
con=null;
}
}
}
JDBCDBUtils 使用PropertiesUtil读取properties文件中数据的用户名密码及url连接数据库获取连接,并定义了关闭连接的方法
mysql.properties文件内容如下
username=root
url=jdbc\:mysql\://localhost\:3306/phptest
driver=com.mysql.jdbc.Driver
password=123456
jdbc连接数据库测试
package mysql;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import util.JDBCDBUtils;
public class JDBCDemo1 {
private static Connection con;
private static Statement state;
private static ResultSet rs;
/**
* @param args
* @throws ClassNotFoundException
* @throws SQLException
*/
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// TODO Auto-generated method stub
try{
con = JDBCDBUtils.getConnect();
state = con.createStatement();
rs = state.executeQuery("select * from myguests");
while (rs.next()) {
System.out.println(
rs.getString(1) + "\t"
+ rs.getString(2) + "\t"
+ rs.getString(3) + "\t"
+ rs.getString(4) + "\t"
+ rs.getString(5));
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
JDBCDBUtils.close(con, state, rs);
}
}
}
结果如下,注意选中的文件
利用c3p0-congig.xml配置文件形式连接数据库
添加依赖
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
配置文件:c3p0-congig.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<named-config name="mvcApp">
<property name="user">root</property>
<property name="password">123456</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/phptest
</property>
<!-- 以上的user是数据库的用户, password是数据库的密码,driverClass是mysql的数据库驱动, jdbcUrl是连接数据库的url -->
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 -->
<property name="acquireIncrement">5</property>
<!--初始化时获取十个连接,取值应在minPoolSize与maxPoolSize之间 -->
<property name="initialPoolSize">10</property>
<!--连接池中保留的最小连接数 -->
<property name="minPoolSize">10</property>
<!--连接池中保留的最大连接数 -->
<property name="maxPoolSize">50</property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default:
0 -->
<property name="maxStatements">20</property>
<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
工具类C3P0DBUtils
package util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0DBUtils {
private static DataSource dataSource = null;
static {
// dataSource资源只能初始化一次
dataSource = new ComboPooledDataSource("mvcApp");
}
/**
* 获取连接
*
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static DataSource getDataSource() {
return dataSource;
}
/**
* 释放连接
*
* @param connection
*/
public static void releaseConnection(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
connection=null;
}
}
public static void close(Connection con,Statement state,ResultSet rs){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("result关闭失败");
}
try {
if(state!=null){
state.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("statement关闭失败");
}
finally {
state=null;
}
try {
if(con!=null){
con.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Connect关闭失败");
}finally {
con=null;
}
}
}
c3p0连接数据库测试
package mysql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import util.C3P0DBUtils;
public class C3P0Demo1 {
public static void main(String[] args) {
try {
Connection con = C3P0DBUtils.getConnection(); // 声明Connection对象
PreparedStatement sql = con.prepareStatement("select * from myguests"); // 声明PreparedStatement对象
ResultSet rs = sql.executeQuery(); // 声明ResultSet对象
while(rs.next()) {
System.out.println(
rs.getString(1) + "\t"
+ rs.getString(2) + "\t"
+ rs.getString(3) + "\t"
+ rs.getString(4) + "\t"
+ rs.getString(5));
}
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
利用dbcp.properties配置文件形式连接数据库
添加依赖
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
dbcp.properties文件内容
###驱动名
driverClassName=com.mysql.jdbc.Driver
###url
url=jdbc:mysql://127.0.0.1:3306/phptest
#用户名
username=root
#密码
password=123456
#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
#最大idle数
maxIdle=10
#最小idle数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1
DBCPUtils工具类
package util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class DBCPUtils {
/**
*
* 获得数据源
* @return
*
*/
static{
PropertiesUtil.setProperties("dbcp.properties");
}
private static Properties props = PropertiesUtil.getProperties();
public static DataSource getDataSource() {
try {
return BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
throw new RuntimeException("获得数据源失败");
}
}
/**
* 获取连接
*
* @return
*/
public static Connection getConnection() {
try {
return getDataSource().getConnection();
} catch (SQLException e) {
throw new RuntimeException("连接数据库失败");
}
}
/**
* 关闭连接
*
* @param conn
* @param prep
* @param rs
*/
public static void close(Connection conn, Statement prep,ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs = null;
}
}
if (prep != null) {
try {
prep.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
prep= null;
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn = null;
}
}
}
}
dbcp连接mysql测试
package mysql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import util.DBCPUtils;
public class DBCPDemo1 {
public static void main(String[] args) {
try {
Connection con = DBCPUtils.getConnection(); // 声明Connection对象
PreparedStatement sql = con.prepareStatement("select * from myguests"); // 声明PreparedStatement对象
ResultSet rs = sql.executeQuery(); // 声明ResultSet对象
while(rs.next()) {
System.out.println(
rs.getString(1) + "\t"
+ rs.getString(2) + "\t"
+ rs.getString(3) + "\t"
+ rs.getString(4) + "\t"
+ rs.getString(5));
}
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}