jdbc连接mysql sqlserver oracle的工具类
package arithmetic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* JDBC连接mysql oracle sqlserver的工具类
* @author liujd
*/
public class JDBCUtil {
//三种数据库url的前缀
private static final String mysql = "jdbc:mysql://";
private static final String oracle = "jdbc:oracle:thin:@";
private static final String sqlServer = "jdbc:microsoft:sqlserver://";
/**
* 获取连接的主入口 根据数据库类型来执行具体的方法
* @param sqlType
* @param url
* @param userName
* @param password
* @return
*/
public static Connection getConnection(String sqlType , String url , String userName , String password) {
if(sqlType.equalsIgnoreCase("mysql")) {
return getMysql(url , userName , password);
}else if(sqlType.equalsIgnoreCase("oracle")) {
return getOracle(url , userName , password);
}else if(sqlType.equalsIgnoreCase("sqlserver")){
return getSqlserver(url , userName , password);
}else{
return null;
}
}
/**
* 获取mysql连接的具体方法
* @param url
* @param userName
* @param password
* @return
*/
private static Connection getMysql(String url, String userName, String password) {
//声明连接对象
Connection conn = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接对象
conn = DriverManager.getConnection(mysql+url, userName, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 获取Oracle连接的具体方法
* @param url
* @param userName
* @param password
* @return
*/
private static Connection getOracle(String url, String userName, String password) {
//声明连接对象
Connection conn = null;
try {
//加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//获取连接对象
conn = DriverManager.getConnection(oracle+url, userName, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 获取sqlserver连接的方法
* @param url
* @param userName
* @param password
* @return
*/
private static Connection getSqlserver(String url, String userName, String password) {
//声明连接对象
Connection conn = null;
try {
//加载驱动
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
//获取连接对象
conn = DriverManager.getConnection(sqlServer+url, userName, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void closeConn(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}