jdbc資料庫連接方式(迭代)
方式五為最終版本
方式一
@Test
public void testConnection() throws SQLException {
// 1.獲取Driver的實作類物件
Driver driver =new com.mysql.jdbc.Driver();
//url:http://localhost:8080/gmail/key.jpg
// jdbc:mysql:協議
// localhost:ip地址
// 3306 默認mysql埠號
// test:test資料庫
String url="jdbc:mysql://localhost:3306/test";
// 將用戶名和密碼封裝在Properties
Properties info=new Properties();
info.setProperty("user", "root");
info.setProperty("password","root");
Connection con=driver.connect(url,info);
System.out.println(con);
}
方式二
// 方式二 對方式一的迭代
// 在如下的程式中不出現第三方的API,使程式具有更好的可移植性
@Test
public void testConnections() throws Exception {
// 1.獲取Driver實作類物件,使用反射
Class cla=Class.forName("com.mysql.jdbc.Driver");
Driver driver=(Driver)cla.newInstance();
// 2.提供連接的資料庫
String url="jdbc:mysql://localhost:3306/test";
// 3.提供連接需要的用戶名和密碼
Properties info=new Properties();
info.setProperty("user", "root");
info.setProperty("password", "root");
// 4.獲取連接
Connection con=driver.connect(url, info);
System.out.println(con);
}
方式三
// 方式三:使用DriverManager替換Driver
@Test
public void testConnection3() throws Exception {
// 1.獲取Driver 實作類物件
Class clazz=Class.forName("com.mysql.jdbc.Driver");
Driver driver=(Driver)clazz.newInstance();
// 2.提供另外三個連接資訊
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="root";
// 注冊驅動
DriverManager.registerDriver(driver);
// 獲取連接
Connection con=DriverManager.getConnection(url,user,password);
System.out.println(con);
}
方式四
// 方式四:可以只是加載驅動,不用顯示的注冊驅動了
@Test
public void testConnection4() throws Exception {
// 1.提供三個連接的基本資訊
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="root";
// 2.加載Driver
Class.forName("com.mysql.jdbc.Driver");
// 相較于方式三,可以省略如下操作
// Driver driver=(Driver)clazz.newInstance();
// 注冊驅動
// DriverManager.registerDriver(driver);
// 為什么可以:
/*在MySQL的Driver實作類中宣告了靜態代碼塊來實作注冊驅動
*
*/
// 3.獲取連接
Connection con=DriverManager.getConnection(url,user,password);
System.out.println(con);
}
方式五(最終版本)
// 方式五:將資料庫連接需要的4個資訊
/*
* 好處:
* 1.實作了資料與代碼的分離,實作了解耦
* 2.如果需要修改組態檔資訊,可以避免程式重新打包
*/
@Test
public void getConnection5() throws Exception {
// 1.讀取組態檔中的4個基本資訊
InputStream is= JdbcCreat1.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pro = new Properties();
pro.load(is);
String user=pro.getProperty("user");
String password=pro.getProperty("password");
String url=pro.getProperty("url");
String driverClass=pro.getProperty("driverClass");
// 2.加載驅動
Class.forName(driverClass);
// 3.獲取連接
Connection con = DriverManager.getConnection(url,user,password);
System.out.println(con);
}
}
-
附帶的組態檔
user=root password=root url=jdbc:mysql://localhost:3306/test driverClass=com.mysql.jdbc.Driver
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/276541.html
標籤:Java
