详解:配置文件properties--JDBCUtil工具类--链接对象Connection--数据库mysql
2022/4/13 19:14:29
本文主要是介绍详解:配置文件properties--JDBCUtil工具类--链接对象Connection--数据库mysql,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1、jdbc每一次创建一个新模块,都需要为该模块重新配置jar包;
2、创建工具类时:属性配文件:db.properties 以及JDBCUtil 工具类放在一个模块中
3、代码实现如下:
##数据库配置信息 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306 jdbc.user=root jdbc.password=root
package com.xzit.platfrom.task.util; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class JDBCUtil { //获取jdbc驱动 public static String driver; //jdbc解析地址 public static String url; //数据库用户名 public static String user; //数据库密码 public static String password; static{ //读取配置文件 InputStream resourceAsStream = JDBCUtil.class.getResourceAsStream("db.properties"); try { //创建properties对象读取属性文件 Properties properties =new Properties(); properties.load(resourceAsStream); driver=properties.getProperty("jdbc.driver"); url=properties.getProperty("jdbc.url"); user=properties.getProperty("jdbc.user"); password=properties.getProperty("jdbc.password"); //输出:数据库信息 System.out.println("数据库驱动:"+driver); System.out.println("数据库url:"+url); System.out.println("数据库用户名:"+user); System.out.println("数据库密码:"+password); //获取数据库驱动 Class.forName(driver); } catch (Exception e) { e.printStackTrace(); }finally { //关闭IO try { resourceAsStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 创建数据库连接对象 * @return * @throws Exception */ public static Connection getConnection()throws Exception{ return DriverManager.getConnection(url,user,password); } /** * 关闭数据库连接资源 * @param conn */ public static void close(Connection conn){ if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 关闭接口对象 * @param stmt */ public static void close( Statement stmt ){ if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 关闭结果集 * @param rs */ public static void close( ResultSet rs ){ if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 创建一个测试文档验证输出结果 * @param args * @throws Exception */ public static void main ( String[] args )throws Exception { System.out.println(getConnection()); } }
这篇关于详解:配置文件properties--JDBCUtil工具类--链接对象Connection--数据库mysql的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-26MySQL查出时间比实际晚8小时的解决方案
- 2024-04-01JPA不识别MySQL的枚举类型
- 2024-03-30mysql数据库表卡死解决方法
- 2024-03-15MySQL多数据源笔记5-ShardingJDBC实战
- 2024-03-11natural join mysql
- 2024-03-11关于VS2017,VS2015 中利用 EF使用Mysql 不显示数据源问题解决方案
- 2024-02-26mysql 阿里云xb后缀备份文件恢复-icode9专业技术文章分享
- 2024-02-22docker mysql 5.7
- 2024-02-18从 20 多套 MySQL 到 1 套 TiDB丨骏伯网络综合运营管理平台应用实践
- 2024-02-07mysql 外键索引入门介绍,为什么工作中很少有人使用?