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连接数据库
1. 配置文件:properties.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8
username=root
password=root
2. 源代码:
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
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/test</property>
<propertyname="driverClass">com.mysql.jdbc.Driver</property>
<propertyname="user">root</property>
<propertyname="password">root</property>
<propertyname="initialPoolSize">3</property>
<propertyname="maxPoolSize">6</property>
<propertyname="maxIdleTime">1000</property>
</default-config>
</c3p0-config>
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
<?xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPEconfiguration
PUBLIC "-//mybatis.org//DTD Config3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environmentsdefault="environment">
<environmentid="environment">
<transactionManager type="JDBC"/>
<dataSourcetype="POOLED">
<propertyname="driver" value="com.mysql.jdbc.Driver" />
<propertyname="url"value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root" />
<propertyname="password" value="root" />
</dataSource>
</environment>
</environments>
<!-- 加载SQL定义文件 -->
<!-- <mappers>
<mapper resource=""/>
</mappers> -->
</configuration>
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
<?xml version='1.0'encoding='utf-8'?>
<!DOCTYPEhibernate-configuration PUBLIC
"-//Hibernate/HibernateConfiguration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接信息 -->
<propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<propertyname="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/test</property>
<propertyname="hibernate.connection.username">root</property>
<propertyname="connection.password">root</property>
<!-- hibernate配置信息 -->
<!-- SQL dialect 方言,用于配置生成针对哪个数据库的-->
<propertyname="dialect">
<!-- 方言类,Hibernate提供的,用于封装某种特定的 -->
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- 生成的sql是否打印到控制台 -->
<propertyname="show_sql">true</property>
<!-- 打印的sql是否进行格式化 -->
<propertyname="format_sql">true</property>
<!-- 在配置文件中关联映射文件 -->
<!-- <mappingresource=""/> -->
</session-factory>
</hibernate-configuration>
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();
}
}
--------------------------------------------------------------------------------------------------------------------------
本内容由安康学院“雨季”原创!