说明:
便于随时切换数据库
步骤:
先创建dbconfig.properties,再编写DBUtils工具类,最后编写DBTest测试类。
参考代码如下:
/**
*dbconfig.properties
*/
#mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ooo
user=root
password=root
#oracle
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#password=tiger
/**
*DBUtils.class
*/
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class DbUtils {
private static String driver;
private static String url;
private static String username;
private static String password;
private static ThreadLocal<Connection> tl = new ThreadLocal<>();
static {
InputStream is = DbUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
Properties prop = new Properties();
try {
prop.load(is);
driver = prop.getProperty("driver");
url = prop.getProperty("url");
username = prop.getProperty("user");
password = prop.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
*获取连接
*/
public static Connection getConnection() {
Connection con = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
/**
*获取事务连接
*/
public static Connection getTransactionConnection() {
Connection con = null;
con = tl.get();
if (con == null) {
con = getConnection();
tl.set(con);
}
return con;
}
/**
*关闭事务连接
*/
public static void closeTransactionConnection() {
Connection con = tl.get();
if (con != null) {
tl.remove();
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
*测试类
*/
import java.sql.Connection;
public class DBTest {
public static void main(String[] args) {
Connection con=DbUtils.getConnection();
System.out.println("con="+con);
}
}
运行结果如下: