Java® 连接 setClientInfo() 方法及其示例


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

参数

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

con.setClientInfo(properties);

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

使用 DriverManager 类 registerDriver() 方法注册驱动程序,如下所示 −

//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());

使用 DriverManager 类 getConnection() 方法获取连接,如下所示 −

//Getting the connection
String url = "jdbc:mysql:///mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");

创建属性对象,如下所示 −

Properties properties = new Properties();

将所需键值对添加到以上创建的 Properties 对象,如下所示 −

properties.put("user_name", "new_user");
properties.put("password", "password");

使用 setClientInfo() 方法将上述创建的属性设置为客户端信息,如下所示 −

//Setting the Client Info
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 {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String url = "jdbc:mysql:///mydatabase";
      Connection con = DriverManager.getConnection(url, "root", "password");
      System.out.println("Connection established......");
      //Adding the credentials of another user to the properties file
      Properties properties = new Properties();
      properties.put("user_name", "new_user");
      properties.put("password", "password");
      //Setting the ClientInfo
      con.setClientInfo(properties);
   }
}

输出

Connection established......

更新于: 2019 年 7 月 30 日

886 次浏览

启动 职业生涯

完成课程获得认证

开始使用
广告
© . All rights reserved.