Java连接setClientInfo()方法和示例
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 = new Properties();
将所需的键值对添加到上面创建的Properties对象中,如下所示:
properties.put("user_name", "new_user");
properties.put("password", "password");使用setClientInfo()方法将上述创建的属性设置为client-info,如下所示:
//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 {
//注册驱动程序
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//获得连接
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
System.out.println("Connection established......");
//将另一个用户的凭证添加到属性文件
Properties properties = new Properties();
properties.put("user_name", "new_user");
properties.put("password", "password");
//设置ClientInfo-
con.setClientInfo(properties);
}
}输出结果
Connection established......