您可以使用getPropertyInfo()
Driver接口的方法获取驱动程序的属性。
DriverPropertyInfo[] info = driver.getPropertyInfo(mysqlUrl, null);
此方法接受两个参数:代表数据库URL的String变量,Properties类的对象,并返回DriverPropertyInfo对象的数组,其中每个对象都包含有关当前驱动程序的可能属性的信息。
从DriverPropertyInfo对象中,您可以获取信息,例如属性名称,属性值,描述,选择以及是否需要(使用字段)名称,值,描述,选择(必需)。
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://localhost/sampledatabase"; //创建MySQL数据库的Driver对象 Driver driver = DriverManager.getDriver(mysqlUrl); //注册驱动程序 DriverManager.registerDriver(driver); //获得连接 Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established: "+con); //获取当前驱动程序的属性 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