jdbc 用Properties连接数据库
时间: 2023-08-26 13:51:57 浏览: 45
要使用 `Properties` 对象连接数据库,可以按照以下步骤进行操作:
1. 创建一个 `Properties` 对象并设置数据库连接属性。
```java
Properties props = new Properties();
props.setProperty("user", "your_username");
props.setProperty("password", "your_password");
props.setProperty("url", "jdbc:mysql://localhost:3306/your_database");
```
在上述代码中,将 `"your_username"` 替换为你的数据库用户名,`"your_password"` 替换为你的数据库密码,`"jdbc:mysql://localhost:3306/your_database"` 替换为你的数据库连接 URL。根据你要连接的数据库类型和配置,需要相应地修改 URL。
2. 使用 `DriverManager` 类的 `getConnection` 方法获取数据库连接对象。
```java
Connection connection = DriverManager.getConnection(props.getProperty("url"), props);
```
在上述代码中,通过调用 `DriverManager.getConnection` 方法,并传入 URL 和 `Properties` 对象作为参数,将返回一个 `Connection` 对象,表示与数据库的连接。
请注意,上述代码是基于使用 JDBC 连接到 MySQL 数据库的情况。确保你已经加载了适当的数据库驱动程序,并提供正确的连接信息(URL、用户名和密码)。
此外,还可以使用 `load` 方法从文件中加载属性:
```java
Properties props = new Properties();
try (InputStream input = new FileInputStream("jdbc.properties")) {
props.load(input);
}
```
在上述代码中,假设 `jdbc.properties` 文件位于项目的根目录中。你可以根据实际情况修改文件路径和名称。
这样,你就可以使用 `Properties` 对象连接数据库了。记得在使用完连接后,关闭数据库连接对象。