Java Connection getClientInfo() 方法示例
jdbcjava 8object oriented programmingprogramming更新于 2025/7/29 1:16:17
Connection 接口的 getClientInfo() 方法返回当前连接的客户端信息属性的名称和值。此方法返回一个属性对象。
检索客户端信息属性文件的值。
使用 DriverManager 类的 registerDriver() 方法将驱动程序注册为 −
//注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver());
使用 DriverManager 类的 getConnection() 方法获取连接,类型为 −
//获取连接 String url = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(url, "root", "password");
创建一个 properties 对象,类型为 −
Properties properties = new Properties();
将所需的键值对添加到上面创建的 Properties 对象中,类型为 −
properties.put("user_name", "new_user");
properties.put("password", "password");
使用 setClientInfo() 方法将上面创建的属性设置为客户端信息,其参数为 −
//设置客户端信息 con.setClientInfo(properties);
使用 getClientInfo() 方法检索属性文件(对象),并通过调用 getProperty() 方法获取属性,其参数为 −
Properties prop = con.getClientInfo();
prop.getProperty("user_name");
prop.getProperty("password");
您也可以直接获取属性,其参数为:
con.getClientInfo("user_name");
con.getClientInfo("password");
以下 JDBC 程序与 MYSQL 数据库建立连接,并将新用户的凭据设置到客户端信息属性文件中。
示例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Connection_getClientInfo {
public static void main(String args[]) throws SQLException {
//注册驱动程序
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//获取连接
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
System.out.println("连接已建立......");
//将其他用户的凭据添加到属性文件
Properties properties = new Properties();
properties.put("user_name","new_user");
properties.put("password","my_password");
//设置 ClientInfo
con.setClientInfo(properties);
//检索 ClientInfo 属性文件中的值
Properties prop = con.getClientInfo();
System.out.println("user name: "+prop.getProperty("user_name"));
System.out.println("password: "+prop.getProperty("password"));
}
}
输出
连接已建立...... user name: new_user password: my_password

