详解:配置文件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()); }
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix