JDBC 筆記02(獲取資料庫連線)
阿新 • • 發佈:2021-02-08
連線的方式一
@Test
public void testConnection_01() throws SQLException {
Driver driver = new com.mysql.jdbc.Driver();
//url = 協議://ip地址:埠號/資料庫
String url = "jdbc:mysql://localhost:3306/mysupermarket";
//將使用者名稱和密碼封裝在Properties中
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","123456");
Connection connect = driver.connect(url, info);
System.out.println(connect);
}
連線的方式二(對方式一的迭代)
@Test
public void testConnection_02 () throws Exception {
//1、獲取Driver實現類物件(反射)
Class aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//2、提供要連線的資料庫
String url = "jdbc:mysql://localhost:3306/mysupermarket";
//3、提供連線需要的使用者名稱和密碼
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","123456");
//4、獲取連線
Connection connect = driver.connect(url, info);
System.out.println(connect);
}
連線的方式三
@Test
public void testConnection_03() throws Exception{
//1、獲取Driver實現類物件(反射)
Class aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//2、提供需要的3個基本資訊
String url = "jdbc:mysql://localhost:3306/mysupermarket";
String user = "root";
String password = "123456";
//3、註冊驅動
DriverManager.registerDriver(driver);
//4、獲取連線
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
連線的方式四(方式三的優化)
@Test
public void testConnection_04() throws Exception{
//1、提供需要的3個基本資訊
String url = "jdbc:mysql://localhost:3306/mysupermarket";
String user = "root";
String password = "123456";
//2、載入Driver
Class.forName("com.mysql.jdbc.Driver");
/*
* 省略了驅動的註冊,
* 因為在mysql的Driver實現類中宣告的
* static{
* try{
* java.aql.DriverManager.registerDriver(new driver);
* }
* catch{
* 、、、、、、
* }
* }
* 語句塊自動註冊了驅動。
* */
//3、獲取連線
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
連線的方式五(最終版)
- 使用配置檔案讀取獲取連線需要的4個基本資訊:
配置檔案程式碼如下:
user=root
password=azhu251264
url=jdbc:mysql://localhost:3306/mysupermarket
driverClass=com.mysql.jdbc.Driver
@Test
public void testConnection_05() throws Exception{
//1、讀取配置檔案
InputStream inputStream = ConnectionTest_01.class.getClassLoader().
getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(inputStream);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClass");
//2、載入驅動
Class.forName(driverClass);
//3、獲取連線
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}