如何使用 JDBC 获取驱动程序的属性?
jdbcobject oriented programmingprogramming
您可以使用 Driver 接口的 getPropertyInfo() 方法获取驱动程序的属性。
DriverPropertyInfo[] info = driver.getPropertyInfo(mysqlUrl, null);
此方法接受两个参数:一个表示数据库 URL 的字符串变量、一个 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("属性名称:"+info[i].name); System.out.println("属性值:"+info[i].value); System.out.println("属性描述:"+info[i].description); System.out.println("选项:"+info[i].choices); System.out.println("是否必需:"+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://localhost/sampledatabase"; //创建 MySQL 数据库的 Driver 对象 Driver driver = DriverManager.getDriver(mysqlUrl); //注册 Driver DriverManager.registerDriver(driver); //获取连接 Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established: "+con); //获取当前 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