jdbc獲取對各種資料庫的連線

不設限發表於2011-12-11
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class ConnectionsManager {
Connection conn;
String user="dada";
String password="dandan";

//獲取對oracle連線
public Connection getOracleConn() throws Exception {
String url="jdbc:oracle:thin:@127.0.0.1:1521:dandan";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection(url,user,password);
return conn;
}

//獲取mysql連線
public Connection getMysqlConn() throws Exception {
String url="jdbc:mysql://127.0.0.1/dandan";
Class.forName("org.gjt.mm.mysql.Driver");
conn=DriverManager.getConnection(url,user,password);
return conn;
}

//獲取sqlServer連線
public Connection getSqlServerConn() throws Exception {
String url="com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");  
conn = DriverManager.getConnection 
 (url,user,password);
return conn;
}

//獲取Odbc連線
public Connection getOdbcConn() throws Exception {
String url="jdbc:odbc:ExcelODBC1";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
conn = DriverManager.getConnection(url, user, password); 
return conn;

//需要注意的是,在使用ODBC進行查詢的時候,跟標準的sql有一些不同
//需要使用"[]"把要查詢的表名字給括起來
// Statement stmt=con.createStatement();
//    ResultSet rs=stmt.executeQuery("select * from [Sheet1$]");
}

//獲取Access連線
public Connection getAccessConn() throws Exception {
String url="jdbc:odbc:test";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
conn = DriverManager.getConnection(url, user, password); 
return conn; 
}

//通過Odbc獲取sqlServer連線
public Connection getSqlServerConn1() throws Exception {
String url="jdbc:odbc:mydb1";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
conn = DriverManager.getConnection(url, user, password); 
//Connection con = DriverManager.getConnection("jdbc:odbc:mydb1;database=pubs", "", ""); 
return conn;
}

}

相關文章