下面的程序介紹瞭如何通過jdbc獲得數據庫的連接,第一個測試方法DriverTest() 是原生的java通過jdbc連接mysql數據庫的一種方法,第二個測試方法CommondriverTest()是通過類路徑下的配置文件來獲得連接信息,從而獲得連接,這種方法不侷限於某種特定的數據庫,而是通用的,只需要改變配置文件即可。
import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Driver;
public class JDBCTest
{
@Test
public void DriverTest() throws SQLException, ClassNotFoundException
{
Driver driver = new com.mysql.jdbc.Driver();
<span style="color:#ff0000;">/* Class.forName("com.mysql.jdbc.Driver");
* 該句和上句效果相同,因爲在載入Driver類的時候,在實現的靜態代碼塊中,Driver接口會自動的創建Driver對象,
* 並自動在DriverManager中進行註冊。
* 附:Driver中的靜態代碼塊:
* static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
*/
</span>
String url = "jdbc:mysql://127.0.0.1:3306/jdbcdb";
Properties info = new Properties(); //properties繼承於HashTable,表示一個鍵值對
info.put("user","root");
info.put("password","root");
<span style="color:#ff0000;">/*
* Connection con = (Connection) DriverManager.getConnection(url,info);
* 該句對應上面註釋的Class.forName(...);來獲得一個連接。
* 在jdbc4之後,其實可以不用使用上面的Class.forName(...);,DriverManager在getConnection的時候,
* 會自動的加載合適的驅動。
*/
</span>
Connection con = (Connection) driver.connect(url,info);
System.out.println(con);
}
//下面的是一個通用的類來獲取任意一種數據庫的連接的方式,它通過讀取jdbc.properties配置文件來獲取相應的連接信息(driverClass,url,user,password)
public Connection getConnection() throws ClassNotFoundException, SQLException, IOException
{
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
//讀取類路徑下的jdbc.properties文件
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
Properties info = new Properties();
info.put("user",user);
info.put("password",password);
//加載Driver類,並獲得連接
Class.forName(driverClass);
Connection con = (Connection) DriverManager.getConnection(jdbcUrl,info);
return con;
}
@Test
public void CommondriverTest() throws ClassNotFoundException, SQLException, IOException
{
System.out.println(getConnection());
}
}
配置信息如下:
<pre class="html" name="code">driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/jdbcdb
user=root
password=root