如何使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP