/**
* 编写数据库连接的工具类,JDBC工具类
* 获取连接对象采用读取配置文件方式
* 读取文件获取连接,执行一次,static{}
* jdbc.properties文件配置
* driver=com.mysql.jdbc.Driver
* url=jdbc:mysql://localhost:3306/day28
* username=root
* password=root1234
*/
public class JDBCUtilsConfig {
private static Connection con;
private static String driverClass;
private static String url;
private static String username;
private static String password;
static {
try {
readConfig();
Class.forName(driverClass);
con = DriverManager.getConnection(url, username, password);
} catch (Exception ex) {
throw new RuntimeException("数据库连接失败");
}
}
private static void readConfig() throws Exception {
//读取jdbc.properties配置文件
InputStream in = JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pro = new Properties();
pro.load(in);
driverClass = pro.getProperty("driverClass");
url = pro.getProperty("url");
username = pro.getProperty("username");
password = pro.getProperty("password");
}
public static Connection getConnection() {
return con;
}
public static void close(Connection con, Statement stat) {
if (stat != null) {
try {
stat.close();
} catch (SQLException ex) {
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
}
}
}
public static void close(Connection con, Statement stat, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException ex) {
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
}
}
}
通过jdbc.properties配置文件实现JDBCUtils工具类
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 首先贴出常规的配置信息代码 ,jdbc.properties: 这里,如果你是自己手动敲上去的,可能会避免prop...
- 进入.ssh文件夹cd ~/.ssh 新建一个config文件touch config 添加以下内容Host *C...