java连接设备连接给参数_Javaweb学习笔记之JDBC(四):从配置文件中读取 数据库连接参数...

package com.demo.utils;

import java.io.FileInputStream;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.Properties;

/**

* 优化 JdbcUtils 工具类,从配置文件中读取数据库连接参数

*/

public class JdbcUtils2 {

private static String url = null;

private static String username = null;

private static String password = null;

private static String driverClass = null;

// 静态代码块,程序一启动的时候就会加载,只加载一次

static {

try {

// 在 java 项目下,可以使用以下方式读取 配置文件;但是,在 web 项目下不可以;

// FileInputStream in = new FileInputStream("./src/db.properties");

/**

* 还有一种加载配置的方式:使用 类路径的方式 加载配置文件,如下所示:

* /:斜杠表示 classpath 的根目录;

* web 项目中的 根目录 从 WEB-INF/classes 目录开始;

* java 项目中的 classpath 根目录从 bin 目录开始;

* 这种方式是通用的,不管是在 java 项目中,还是在 web 项目中;

*/

InputStream in = JdbcUtils.class.getResourceAsStream("/db.properties");

// 加载配置文件

Properties prop = new Properties();

prop.load(in);

// 读取配置文件

url = prop.getProperty("url");

username = prop.getProperty("username");

password = prop.getProperty("password");

driverClass = prop.getProperty("driverClass");

// 注册驱动程序

Class.forName(driverClass);

}catch (Exception e){

e.printStackTrace();

}

}

/**

* 获取 数据库连接对象

*/

public static Connection getConnection() {

try {

// 获取数据库连接对象

return DriverManager.getConnection(url, username, password);

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

/**

* 释放资源:后创建的先释放

*

* @param conn Connection 对象

* @param stmt PreparedStatement 对象

* @param rs ResultSet 对象

*/

public static void close(Connection conn, Statement stmt, ResultSet rs) {

if (rs != null){

try {

rs.close();

}catch (Exception e){

e.printStackTrace();

throw new RuntimeException(e);

}

}

if (stmt != null) {

try {

stmt.close();

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

if (conn != null) {

try {

conn.close();

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

}

}

db.properties 文件为:

a8c010d4881f7c8154a2fdfba46e7fee.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值