您的位置:首页 > 编程语言 > Java开发

java中连接MySQL数据库的几种方式

2017-09-12 15:49 561 查看
1.DBCP连接池连接数据库

1.1概念

DBCP(DataBase Connection Pool)数据库连接池,是java数据库连接池的一种,由Apache开发,通过数据库连接池,可以让程序自动管理数据库连接的释放和断开。

1.2代码示例

所需jar包:commons-dbcp2-2.2.1.jar、commons-pool2-2.4.2.jar、commons-logging-1.2.jar,另外还有数据库的jdbc驱动mysql-connector-java-5.1.40-bin.jar 

连接池管理类

package com.wqc.test;
 
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.Properties;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
 
public class DBManager {
private static final String configFile = "dbcp.properties";
 
private static DataSource dataSource;
 
static {
Properties dbProperties = new Properties();
try {
dbProperties.load(DBManager.class.getClassLoader().getResourceAsStream(configFile));
dataSource = BasicDataSourceFactory.createDataSource(dbProperties);
 
Connection conn = getConn();
DatabaseMetaData mdm = conn.getMetaData();
 
System.out.println("Connected to " + mdm.getDatabaseProductName() + " " + mdm.getDatabaseProductVersion());
if (conn != null) {
conn.close();
}
 
} catch (Exception e) {
System.out.println("初始化连接池失败:" + e);
}
}
 
private DBManager() { 
}
 
public static final Connection getConn() {
Connection conn = null;
try {
conn = dataSource.getConnection();
} catch (Exception e) {
System.out.println("获取数据库连接失败:" + e);
}
return conn;
}
 
//关闭数据库连接,将连接返还给数据库连接池
public static void closeConn(Connection conn) {
try {
if (conn != null && !conn.isClosed()) {
conn.setAutoCommit(true);
conn.close();
}
} catch (Exception e) {
System.out.println("关闭数据库连接失败:" + e);
}
}
 
public static void main(String[] args) {
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
Connection conn = DBManager.getConn();
System.out.println(i + "连接数:");
DBManager.closeConn(conn);
}
long end = System.currentTimeMillis();
System.out.println("用时:" + (end - begin));
}
}
1. 配置文件需要放在src文件夹下,内容如下:

 

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=123456
maxActive=30
maxIdle=10
maxWait=1000
removeAbandoned=true
removeAbandonedTimeout=180
 

2.利用DriverManager连接数据库

2.1最简单粗暴的方法

public  static Connection getConnection() throws ClassNotFoundException{

String url="jdbc:mysql:///jdbc";//我连的数据库是MySQL中的jdbc数据库

String username="root";

String password="";//我的MySQL数据库的密码是空字符串

String driverClass="com.mysql.jdbc.Driver";

Connection ct=null;

Class.forName(driverClass);

try {

ct=DriverManager.getConnection(url, username, password);

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return ct;

}

2.2利用io流读取文件的方式

public static Connection getConnection() throws ClassNotFoundException, IOException {

String driver = null;

String jdbcurl = null;

String user = null;

String password = null;

// 读取类路径下的jdbc.propreties文件(配置文件)

InputStream in = JDBCtool.class.getClassLoader().getResourceAsStream("jdbc.properties");

// 以上为输入流

Properties pt = new Properties();// 创建properties

pt.load(in);// 取键值对(加载对应的输入流)

driver = pt.getProperty("driver");

jdbcurl = pt.getProperty("jdbcurl");

user = pt.getProperty("user");

password = pt.getProperty("password");

Connection ct = null;

Class.forName(driver);

try {

ct = DriverManager.getConnection(jdbcurl, user, password);

 

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return ct;

}

将diver、jdbcurl、user、password这些信息存储到类路径下的jdbc.propreties文件中(以下是该文件中的内容)

 
 

2、利用c3p0连接池连接数据库

准备工作:

1、导入c3p0的jar包,切记一定要把其相依赖的jar包——mchange-commons-java-0.2.3.4.jar也导进来。   

 

 2、编写c3p0-config.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <named-config name="helloc3p0">
<!--     连接数据源的基本属性 -->
    <property name="user">root</property>
     <property name="password"></property>
     <property name="driverClass">com.mysql.jdbc.Driver</property>

     <property name="jdbcUrl">jdbc:mysql:///jdbc</property>
    
<!--     若数据库中连接数不足时,一次向数据库服务器申请多少个连接  -->
    <property name="acquireIncrement">5</property>
<!--      初始化数据库连接池时连接的数量 -->
    <property name="initialPoolSize">5</property>
<!--     数据库连接池中的最小的数据库连接数 -->
    <property name="minPoolSize">5</property>
    <!--     数据库连接池中的最大的数据库连接数 -->
    <property name="maxPoolSize">10</property>
<!--     c3p0数据库连接可以维护的statement的个数 -->
    <property name="maxStatements">20</property>
<!--     每个连接同时可以使用的statement对象的个数 -->
    <property name="maxStatementsPerConnection">5</property>
    </named-config>
</c3p0-config>
 
获取数据库连接的代码如下:
private static DataSource ds=null;
//数据库连接池应只被初始化一次
static{
ds=new ComboPooledDataSource("helloc3p0");
}
//获取数据库连接
public static  Connection getConnection() throws ClassNotFoundException, SQLException, IOException{
return ds.getConnection();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: