如何使用 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