日常的時候,經常有同學問有關如何串連到資料庫的問題,現在寫下來,希望對有的人,有些協助。
1. 載入一個對應資料庫的JDBC驅動
在建立到一個資料庫的串連之前,必須先載入這個資料庫的JDBC驅動程式,載入之後此driver會自動註冊到JDBC驅動列表中。載入一個JDBC驅動有兩種方法。
a) 在命令列方式下指定磁碟機或者用冒號分割磁碟機列表:
具體命令如下:
C:/>java –Djdbc.drivers = com.company1.Driver:com.company2.Driver youProject
b)第二種方法,在程式中調用Class.forName()方法。推薦使用。。。。
try
{
String driverName = “com.imaginary.sql.msql.MsqlDriver”;
Class.forName(driverName).newInstance();
}
Catch(ClassNotFoundException e1)
{
//catch could not find database driver exception.
}
2.串連到資料庫。
根據您後台待串連的資料庫不同,而有小小的差別。
a) 串連到Oracle資料庫。
Connection connection = null ;
try
{
//load the jdbc driver ;
String driverName = “oracle.jdbc.driver.OracleDriver”;
Class.forName(driverName).newInstance();
//create a connection to the database;
String serverName = “127.0.0.1”;
String serverPort = “1521”;
String serverID = “datebase1”
String userName = “hello”;
String userPsw = “world”;
String url = “jdbc:oracle.thin:@” + serverName + “:” + serverPort + “:” + serverID ;
Connection = DriverManager.getConnection(url , userName , userPsw);
}
catch(ClassNotFoundException e1)
{
//catch could not find database driver exception.
}
catch(SQLException e2)
{
//catch could not connect to the database exception.
}
b) 串連到一個SQL Server資料庫。
Connection connection = null ;
try
{
//load the jdbc driver ;
String driverName = “com.microsoft.jdbc.sqlserver.SQLServerDriver”;
Class.forName(driverName).newInstance();
//create a connection to the database;
String serverName = “127.0.0.1”;
String serverPort = “1433”;
String serverID = serverName + serverPort ;
String userName = “hello”;
String userPsw = “world”;
String url = “jdbc:JSQLConnect ://” + serverID ;
Connection = DriverManager.getConnection(url , userName , userPsw);
}
catch(ClassNotFoundException e1)
{
//catch could not find database driver exception.
}
catch(SQLException e2)
{
//catch could not connect to the database exception.
}
c) 串連到一個MySQL資料庫上。。。。
Connection connection = null ;
try
{
//load the jdbc driver ;
String driverName = “org.gjt.mm.mysql.Driver”;
Class.forName(driverName).newInstance();
//create a connection to the database;
String serverName = “127.0.0.1”;
String serverID = “database”;
String userName = “hello”;
String userPsw = “world”;
String url = “jdbc:mysql ://” + serverName + “/” + serverID ;
Connection = DriverManager.getConnection(url , userName , userPsw);
}
catch(ClassNotFoundException e1)
{
//catch could not find database driver exception.
}
catch(SQLException e2)
{
//catch could not connect to the database exception.
}
綜合上面的三種資料庫連接方式 , 其實大同小異。由於訪問不同的資料庫和所使用的資料庫驅動程式不同,所以導致代碼錶面上有小小不同,但透過表面看來,內部都是
1. 載入一個特定的資料庫JDBC驅動。
2. 串連到一個資料庫。
3. 之後,就可以對一個特定的資料庫進行特定的操作了。