Java连接数据库的几种方式
程序预览图:
第一种:最普通的方式,利用java原生jdbc连接数据库
package utils;
import java.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
import java.sql.ResultSet;
importjava.sql.SQLException;
public class JDBCUtilsDemo1{
static{
/**
*1. 加载驱动
*/
try {
Class.forName("com.mysql.jdbc.Driver"); //利用反射加载驱动
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 2.建立连接
*/
public static Connection getConnection() {
try {
returnDriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8","root", "root");
} catch (SQLException e) {
throw newRuntimeException(e);
}
}
/**
* 关闭连接
* @param conn
* @param prep
* @param rs
*/
public static void close(Connection conn,PreparedStatementprep,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;
}
}
}
/**
* 测试数据库连通性
*/
public static void main(String[] args) {
Connection conn=JDBCUtilsDemo1.getConnection();
System.out.println(conn);
JDBCUtilsDemo1.close(conn,null, null);
}
}
第二种:利用properties.properties配置文件形式,利用java原生jdbc连接数据库
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8
username=root
password=root
package utils;
import java.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
import java.sql.ResultSet;
importjava.sql.SQLException;
import java.util.Properties;
public class JDBCUtilsDemo2{
private static Properties prop;
static {
prop = new Properties();
try {
prop.load(JDBCUtilsDemo2.class.getClassLoader().getResourceAsStream(
"db.properties"));
Class.forName(prop.getProperty("driver"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection(Connection conn) {
if (conn==null) {
try {
conn=DriverManager.getConnection(prop.getProperty("url"),
prop.getProperty("username"),prop.getProperty("password"));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return conn;
}
public static void close(Connection conn,PreparedStatementprep,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;
}
}
}
public static voidmain(String[] args) {
Connection conn = null;
conn=JDBCUtilsDemo2.getConnection(conn);
System.out.println(conn);
JDBCUtilsDemo2.close(conn,null, null);
}
}
第三种:利用c3p0-congig.xml配置文件形式,利用c3p0连接数据库
1.配置文件:c3p0-congig.xml
jdbc:mysql://127.0.0.1:3306/test
com.mysql.jdbc.Driver
root
root
3
6
1000
2.源代码:
package utils;
import java.sql.Connection;
importjava.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
importcom.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBCUtilsDemo3{
/**
* 获得一个数据源
*/
private staticDataSource dataSource=new ComboPooledDataSource();
public staticDataSource getDataSources() {
return dataSource;
}
/**
* 获取连接
*/
public staticConnection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 关闭连接
* @param conn
* @param prep
* @param rs
*/
public static void close(Connectionconn,PreparedStatement 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;
}
}
}
/**
* 测试数据库连通性
*/
public static void main(String[] args) {
Connection conn = null;
conn=JDBCUtilsDemo3.getConnection();
System.out.println(conn);
JDBCUtilsDemo1.close(conn,null, null);
}
}
第四种:利用dbcp.properties配置文件形式,利用dbcp连接数据库
1配置文件:dbcp.properties
########DBCP配置文件##########
#####驱动名
driverClassName=com.mysql.jdbc.Driver
#####url
url=jdbc:mysql://127.0.0.1:3306/test
#####用户名
username=root
#####密码
password=root
#####初试连接数
initialSize=30
#####最大活跃数
maxTotal=30
#####最大idle数
maxIdle=10
#####最小idle数
minIdle=5
#####最长等待时间(毫秒)
maxWaitMillis=1000
####程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#####removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
####连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1
2.源代码:
package utils;
import java.io.IOException;
import java.sql.Connection;
importjava.sql.PreparedStatement;
import java.sql.ResultSet;
importjava.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
importorg.apache.commons.dbcp.BasicDataSourceFactory;
public class JDBCUtilsDemo4{
private static Properties props = new Properties();
static {
// 加载配置文件
try {
props.load(JDBCUtilsDemo4.class.getClassLoader()
.getResourceAsStream("dbcp.properties"));
} catch (IOException e) {
throw new RuntimeException("配置文件加载失败");
}
}
/**
* 获得数据源
*
* @return
*/
public static DataSource getDataSource() {
try {
returnBasicDataSourceFactory.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, PreparedStatementprep,
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;
}
}
}
/**
* 测试数据库连通性
*/
public static void main(String[] args) {
Connection conn = null;
conn = JDBCUtilsDemo4.getConnection();
System.out.println(conn);
JDBCUtilsDemo4.close(conn, null, null);
}
}
第五种:利用mybatis-config.xml配置文件形式,利用MyBatis连接数据库
1配置文件:mybatis-config.xml
2.源代码:
package utils;
importorg.apache.ibatis.session.SqlSession;
importorg.apache.ibatis.session.SqlSessionFactoryBuilder;
public class JDBCUtilsDemo5{
private staticSqlSession session=null;
public static SqlSession getSession(){
try {
session= newSqlSessionFactoryBuilder().build(JDBCUtilsDemo5.class.getClassLoader().getResourceAsStream("mybatis-config.xml")).openSession();
} catch (Exception e) {
throw new RuntimeException(e);
}
return session;
}
public static void close() {
if(session!=null) {
session.close();
}
}
public static void main(String[] args) {
SqlSessionsession=null;
session=JDBCUtilsDemo5.getSession();
System.out.println(session);
JDBCUtilsDemo5.close();
}
}
第六种:利用hibernate.cfg.xml配置文件形式,利用hibernate连接数据库
1配置文件hibernate.cfg…xml
com.mysql.jdbc.Driver
jdbc:mysql://127.0.0.1:3306/test
root
root
org.hibernate.dialect.MySQL5Dialect
true
true
2.源代码:
package utils;
import org.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.hibernate.cfg.Configuration;
@SuppressWarnings("deprecation")
public class JDBCUtilsDemo6{
private static Configuration config;
private static SessionFactory sessionFactory;
private static Session session;
static {
// 1.加载hibernate.cfg.xml配置文件
config = new Configuration().configure();
// 2.获取SessionFactory
sessionFactory = config.buildSessionFactory();
}
// 3.得到session
public static Session getSession() {
session = sessionFactory.openSession();
return session;
}
// 4.关闭session
public static void close() {
if (session != null) {
session.close();
}
}
public static void main(String[] args) {
Session session = JDBCUtilsDemo6.getSession();
System.out.println(session);
JDBCUtilsDemo6.close();
}
}