各种数据库的连接连接Connection方法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
package com.jdbc.myConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionFactory
{
//获取Oracle连接
public static Connection getOracleConnection()
{
Connection con = null;
try {
Class.forName("oracle.jdbc.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
con = DriverManager.getConnection(url, "scott", "tiger");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
//获取SQLServer的test数据库连接
public static Connection getSQLServerConnection() {
return getMySQLConnection("test");
}
//获取SQLServer 连接
public static Connection getSQLServerConnection(String databaseName) {
Connection con = null;
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String url = "jdbc:microsoft:sqlServer://localhost:1433;databaseName=" + databaseName;
con = DriverManager.getConnection(url, "sa", "sa");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
//获取MySQL连接
public static Connection getMySQLConnection() {
return getMySQLConnection("test");
}
public static Connection getMySQLConnection(String databaseName) { Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/" + databaseName;
con = DriverManager.getConnection(url, "root", "root");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
//关闭连接
public static void close(Connection con) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}