如何使用 JDBC 獲取驅動的屬性?


可以使用 Driver 介面的 getPropertyInfo() 方法來獲取驅動的屬性。

DriverPropertyInfo[] info = driver.getPropertyInfo(mysqlUrl, null);

此方法接受兩個引數:代表資料庫 URL 的 String 變數、Properties 類的物件,並返回 DriverPropertyInfo 物件陣列,其中每個物件都包含有關當前驅動程式的可能屬性的資訊。

DriverPropertyInfo 物件中,你可以獲取有關屬性名稱、屬性值、描述、選項以及是否必需等資訊,使用其欄位分別為 name、value、description、choices、required

DriverPropertyInfo[] info = driver.getPropertyInfo(mysqlUrl, null);
for (int i = 0; i < info.length; i++) {
   System.out.println("Property name: "+info[i].name);
   System.out.println("Property value: "+info[i].value);
   System.out.println("Property description: "+info[i].description);
   System.out.println("Choices: "+info[i].choices);
   System.out.println("Is Required: "+info[i].required);
   System.out.println(" ");
}

以下 JDBC 程式建立與 MySQL 資料庫的連線,並獲取當前驅動程式所需屬性的名稱、值、描述和選項。

示例

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
public class DriverPropertyinfoExample {
   public static void main(String args[]) throws Exception {
      String mysqlUrl = "jdbc:mysql:///sampledatabase";
      //Creating a Driver object of the MySQL database
      Driver driver = DriverManager.getDriver(mysqlUrl);
      //Registering the Driver
      DriverManager.registerDriver(driver);
      //Getting the connection
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established: "+con);
      //Getting the properties of the current driver
      DriverPropertyInfo[] info = driver.getPropertyInfo(mysqlUrl, null);
      for (int i = 0; i < info.length; i++) {
         if(info[i].required) {
            System.out.print("Property name: "+info[i].name+", ");
            System.out.print("Property value: "+info[i].value+", ");
            System.out.print("Property description: "+info[i].description+", ");
            System.out.print("Choices: "+info[i].choices);
            System.out.println(" ");
         }
      }
   }
}

輸出

Connection established: com.mysql.jdbc.JDBC4Connection@6d1e7682
Property name: HOST, Property value: localhost, Property description: Hostname of MySQL Server, Choices: null
Property name: user, Property value: null, Property description: Username to authenticate as, Choices: null
Property name: password, Property value: null, Property description: Password to use for authentication, Choices: null

更新於:30-Jul-2019

768 次瀏覽

開啟你的職業生涯

透過完成課程獲取認證

開始學習
廣告