JDBCUtil工具类
package com.lingyi.sync.util;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.*;
import java.util.*;
import java.util.Date;
public class JdbcUtil {
private static Logger logger = Logger.getLogger(JdbcUtil.class.getClass());
public static enum DatabaseType {
Oracle("oracle"),
SQL_Server("sqlserver"),
MySQL("mysql");
private String name;
private DatabaseType(String name) {
this.name = name;
}
public String getName() {
return name;
}
};
private static Properties props;
private static String filePath =null;
static {
URL url = JdbcUtil.class.getProtectionDomain().getCodeSource().getLocation();
try {
filePath = URLDecoder.decode(url.getPath(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
filePath = filePath.replace("target/classes/", "");
if (filePath.endsWith(".jar")) {
filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
}
if (System.getProperty("os.name").contains("dows")){
File file = new File(filePath);
filePath = file.getAbsolutePath();
}
}
static {
try {
props = new Properties();
InputStream in = new FileInputStream(new File(filePath + "/config/chemical_db.properties"));
props.load(in);
} catch (IOException e) {
LogUtil.insert(new Date(),"安全考试系统","错误信息","加载外部配置文件失败");
throw new RuntimeException("没有找到外部配置文件");
}
}
public static Connection getConnection(DatabaseType type){
try {
Class.forName(props.getProperty(type.getName() + ".driver"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String jdbcUrl = props.getProperty(type.getName() + ".jdbcUrl");
String user = props.getProperty(type.getName() + ".user");
String password = props.getProperty(type.getName() + ".password");
try {
return DriverManager.getConnection(jdbcUrl, user, password);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("连接数据库失败");
}
}
public static void releaseDB(PreparedStatement ps) {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void releaseDB(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
#MySQL
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.jdbcUrl=jdbc:mysql://localhost:3306/labv2
mysql.user=root
mysql.password=root
#Oracle
oracle.driver=oracle.jdbc.driver.OracleDriver
oracle.jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
oracle.user=
oracle.password=
#sql_server
sqlserver.driver=
sqlserver.jdbcUrl=
sqlserver.user=
sqlserver.password=