Java如何使用Properties建立与数据库的连接?
在以下代码片段中,您将看到在连接数据库时如何传递一些连接参数。为此,我们可以使用java.util.Properties该类。在将这些信息传递给DriverManager类之前,我们可以将一些键值对作为Properties对象的连接参数。
让我们看下面的例子:
package org.nhooo.example.jdbc; import java.sql.*; import java.util.Properties; public class GetConnectionWithProperties { private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { GetConnectionWithProperties demo = new GetConnectionWithProperties(); try (Connection connection = demo.getConnection()) { // 对连接做一些事情。 Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM products"); while (rs.next()) { System.out.println("Code = " + rs.getString("code")); System.out.println("Name = " + rs.getString("name")); } } catch (SQLException e) { e.printStackTrace(); } } private Connection getConnection() throws SQLException { Properties connectionProps = new Properties(); connectionProps.put("user", USERNAME); connectionProps.put("password", PASSWORD); Connection connection = DriverManager.getConnection(URL, connectionProps); System.out.println("Connected to database."); return connection; } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>