本文提供了一种在Java中实现数据库连接工具类的方法,具体如下:
1.配置文件
配置文件db.properties内容如下:
#mysql
classname=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/stock
username=root
pwd=1234567890
#oracle
#classname=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@192.168.0.26:1521:tarena
#username=jsd1307
#pwd=jsd1307
2.工具类代码
进行数据库连接相关操作的代码如下:
package util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* 工具类,提供连接
*
* @author cobcmw
*
*/
public class DBUtil {
private static ThreadLocal<Connection> connections = new ThreadLocal<Connection>();
private static Properties props = new Properties();
static {
InputStream ips = DBUtil.class.getClassLoader().getResourceAsStream(
"util/db.properties");
try {
props.load(ips);
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取db.properties文件失败");
}
}
private static String className = props.getProperty("classname");
private static String url = props.getProperty("url");
private static String username = props.getProperty("username");
private static String pwd = props.getProperty("pwd");
public static void beginTranaction() throws SQLException {
try {
Connection conn = getConnection();
conn.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
System.out.println("启动事务失败");
throw e;
}
}
public static void commit() throws SQLException {
try {
Connection conn = getConnection();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("提交事务失败");
throw e;
} finally {
close();
}
}
public static void rollback() throws SQLException {
try {
Connection conn = getConnection();
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("回滚事务失败");
throw e;
} finally {
close();
}
}
public static Connection getConnection() throws SQLException {
Connection conn = connections.get();
if (conn == null) {
conn = getConn();
connections.set(conn);
}
return conn;
}
public static void close() {
Connection conn = connections.get();
if (conn != null) {
try {
conn.close();
connections.set(null);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static Connection getConn() throws SQLException {
Connection conn = null;
try {
Class.forName(className);
conn = DriverManager.getConnection(url, username, pwd);
} catch (ClassNotFoundException e) {
// 记日志
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
throw e;
}
return conn;
}
/**
* 关闭连接
*/
private static void close(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
System.out.println(getConnection());
}
}
最新评论
我的是ipv4网络,如何使用直播源啊!
我今天试了,不想啊,我的是新疆昌吉移动的网络。
收不到验证码电报
现在充值29起了