Java Connection The setClientInfo() method with example

JDBCJava 8Object Oriented ProgrammingProgramming

The setClientInfo() method of the Connection interface sets values to the client info properties of the current connection object.

Parameters

This method accepts a Properties object as a parameter.

con.setClientInfo(properties);

To set values to the client info properties file.

Register the driver using the registerDriver() method of the DriverManager class as −

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

Get the connection using the getConnection() method of the DriverManager class as −

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

Create a properties object as −

Properties properties = new Properties();

Add the required key-value pairs to the above created Properties object as −

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

Set the above created properties to the client-info using the setClientInfo() method as −

//Setting the Client Info
con.setClientInfo(properties);

Following JDBC program establishes connection with the MYSQL database and sets the credentials of a new user to the client info properties file.

Example

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://localhost/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);
   }
}

Output

Connection established......
raja
Published on 15-May-2019 11:51:43
Advertisements