Java 连接 setClientInfo() 方法示例

jdbcjava 8object oriented programmingprogramming更新于 2025/7/22 12:28:17

Connection 接口的 setClientInfo()  方法用于设置当前连接对象的客户端信息属性值。

参数

此方法接受一个 Properties 对象作为参数。

con.setClientInfo(properties);

设置客户端信息属性文件的值。

使用 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);

以下 JDBC 程序将与 MYSQL 数据库建立连接,并将新用户的凭据设置为客户端信息属性文件。

示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Connection_setClientInfo {
   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","password");
      //设置 ClientInfo
      con.setClientInfo(properties);
   }
}

输出

连接已建立......

相关文章