MySql,Oracle,SqlServer的获取链接
/**
* 连接超时时间,使用配置,默认30s
*/
private int connectTimeout = 30000;
/**
* socket超时时间,使用配置,默认30s
*/
private int socketTimeout = 30000;
/**
* SQL超时时间,使用配置,默认30s
*/
private int queryTimeout = 30000;
Connection conn = null;
String driver = ""; //jdbc驱动类名
String url = ""; //连接URL
//Oracle超时属性对象
Properties connProps = new Properties();
//设置driver和url
if(StringUtils.containsIgnoreCase(dbConn.getType(), DatabaseType.MSSQL)) {
driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
url = MessageFormat.format("jdbc:sqlserver://{0}:{1}; DatabaseName={2}",
new Object[]{ dbConn.getServer(), dbConn.getPort(), dbConn.getDatabase() });
//设置超时时间,转换单位为s
connectTimeout /= 1000;
socketTimeout /= 1000;
url = url+";loginTimeout="+connectTimeout+";socketTimeout="+socketTimeout;
} else if(StringUtils.containsIgnoreCase(dbConn.getType(), DatabaseType.MYSQL)) {
driver = "com.mysql.jdbc.Driver";
url = MessageFormat.format("jdbc:mysql://{0}:{1}/{2}",
new Object[]{ dbConn.getServer(), dbConn.getPort(), dbConn.getDatabase() });
//url = url + "?autoReconnect=true&failOverReadOnly=false&maxReconnects=10&connectTimeout=120000&socketTimeout=120000"; //防止获取不到连接
url = url + "?characterEncoding=utf8&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&maxReconnects=10&connectTimeout="+connectTimeout+"&socketTimeout="+socketTimeout+"&useSSL=false"; //防止获取不到连接
} else if(StringUtils.containsIgnoreCase(dbConn.getType(), DatabaseType.ORACLE)) {
driver = "oracle.jdbc.driver.OracleDriver";
url = MessageFormat.format("jdbc:oracle:thin:@{0}:{1}:{2}",
new Object[]{ dbConn.getServer(), dbConn.getPort(), dbConn.getDatabase() });
connProps.put("oracle.net.CONNECT_TIMEOUT",""+connectTimeout);
connProps.put("oracle.jdbc.ReadTimeout",""+socketTimeout);
}
connProps.put("user",dbConn.getUsername());
connProps.put("password",dbConn.getPassword());
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,connProps);
} catch (ClassNotFoundException | SQLException e) {
log.error("获取数据库连接失败", e);
throw e;
}
return conn;
Oracle:
url: jdbc:oracle:thin:@192.168.90.99:1521:Orcl
SQLServer: jdbc:sqlserver://192.168.90.99:1433; DatabaseName=test