如何使用 JDBC 中的属性文件与数据库建立连接?

jdbcjava 8object oriented programmingprogramming

DriverManager  类的 getConnection() 方法的一个变体接受数据库的 url、(字符串格式)属性文件并与数据库建立连接。

Connection con = DriverManager.getConnection(url, properties);

使用此方法与数据库建立连接 −

将 Driver 类名称设置为系统属性 −

System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver");

创建一个 properties 对象作为 −

Properties properties = new Properties();

将用户名和密码作为 − 添加到上面创建的 Properties 对象中

properties.put("user", "root");
properties.put("password", "password");

最后通过传递 URL 和 properties 对象作为参数来调用 DriverManager  类的 getConnection()  方法。

//获取连接
String url = "jdbc:mysql://localhost/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 {
      //注册驱动程序
      System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver");
      Properties properties = new Properties();
      properties.put(&"user&", &"root");
      properties.put(&"password", &"password");
      //获取连接
      String url = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(url, properties);
      System.out.println("Connection established: "+ con);
   }
}

输出

Connection established: com.mysql.jdbc.JDBC4Connection@2db0f6b2

相关文章