本文提供了一种在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());
}
}
最新评论
网飞没问题, 迪士尼+有解决方案么?
pp助手是安卓手机用的,根本下载用不来苹果
已解决
这样的话数据库里的结构为{"attachment":{"content":"xxx"}}, 要怎么才能变成{"content":"xxx"},从而使结构保持一致?
赞! make test不过的坑都写到的,谢谢楼主~
谢谢你
用了root用户还是一直502是怎么回事呢
student id 是空的