java中连接MySQL数据库的几种方式
2017-09-12 15:49
561 查看
1.DBCP连接池连接数据库
连接池管理类
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
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;
}
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文件中(以下是该文件中的内容)
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();
}
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();
}
相关文章推荐
- java中几种常见的连接MySQL数据库的方式
- Java连接数据库的几种方式
- Mysql数据库的几种连接方式
- Java项目中连接数据库的几种方式和范例
- java连接Hive的几种方式
- 请教评价java连接数据库的几种不方式
- JAVA连接MySQL数据库(可转换成SQL Server、Oracle连接方式)(精华版)
- java连接数据库的几种方式
- java获取MySql数据库的连接方式案例
- php连接mysql数据库的几种方式(mysql、mysqli、pdo)
- java基础—连接MySQL数据库的2种常用方式(传统方式和c3p0连接池)
- java连接数据库的几种方式(转)
- [笔记]通过命令行连接MySQL数据库服务器的几种方式总结如下
- java连接sql2005几种方式
- PHP连接MySQL数据库的几种方式
- php连接mysql数据库的几种方式(mysql、mysqli、pdo)
- java自定义注解的方式连接MySQL数据库来走进注解
- Java字符串连接的几种方式
- java使用JDBC连接数据库的几种方式
- java使用JDBC连接数据库的几种方式