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.