JDBC工具类提取:
常见的配置文件格式:
1.properties
格式 key=value
2.xml
若我们的配置文件为properties,且放在src目录下,可通过ResourceBundle工具快速获取里面的配置信息
使用步骤:
1.获取ResourceBundle对象
static ResourceBundle getBundle("文件名称不带后缀")
2.通过ResourceBundle 对象获取配置信息
String getString(String key):通过key值获取指定的value
package com.company.utils; import java.sql.*; import java.util.ResourceBundle; public class JdbcUtils { static final String DRIVERCLASS; static final String URL; static final String USER; static final String PASSWORD; //获取连接 static { ResourceBundle rb = ResourceBundle.getBundle("jdbc"); DRIVERCLASS = rb.getString("driverClass"); URL = rb.getString("url"); USER = rb.getString("user"); PASSWORD = rb.getString("password"); } public static Connection getCon() throws Exception { //连接驱动 Class.forName(DRIVERCLASS); //获取连接 return DriverManager.getConnection(URL,USER,PASSWORD); } //释放资源 public static void closeResource(Connection con, Statement st,ResultSet rs){ closeCon(con); closeStatement(st); closeResultSet(rs); } /** * 释放连接 * @param con 连接 */ public static void closeCon(Connection con){ if(con!=null){ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } con = null; } /** * 释放语句执行者 * @param st 语句执行者 */ public static void closeStatement(Statement st){ if(st!=null){ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } st = null; } /** * 释放结果集 * @param rs 结果集 */ public static void closeResultSet(ResultSet rs){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } rs = null; } }