如何使用 JDBC 中的属性文件与数据库建立连接?
getConnection() 方法的 DriverManager 类的变体之一接受数据库的 url(字符串格式)、一个属性文件,并与数据库建立连接。
Connection con = DriverManager.getConnection(url, properties);
要使用此方法与数据库建立连接,请执行以下操作:-
将驱动器类名设为系统属性 -
System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver");创建一个属性对象,如下所示 -
Properties properties = new Properties();
将用户名和密码添加到上面创建的属性对象,如下所示 -
properties.put("user", "root");
properties.put("password", "password");最后调用DriverManager 类的getConnection() 方法,并传递 URL 和属性对象作为参数。
//Getting the connection String url = "jdbc:mysql:///mydatabase"; Connection con = DriverManager.getConnection(url, properties);
以下 JDBC 程序使用属性文件与 MySQL 数据库建立连接。
示例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class EstablishingConnectionUsingProperties {
public static void main(String args[]) throws SQLException {
//Registering the Driver
System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver");
Properties properties = new Properties();
properties.put("user", "root");
properties.put("password", "password");
//Getting the connection
String url = "jdbc:mysql:///mydatabase";
Connection con = DriverManager.getConnection(url, properties);
System.out.println("Connection established: "+ con);
}
}输出
Connection established: com.mysql.jdbc.JDBC4Connection@2db0f6b2
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP