JDBCUtils工具类的属性

mac2022-06-30  28

package cn.itcast.util;import java.io.FileReader;import java.io.IOException;import java.net.URL;import java.sql.*;import java.util.Properties;/** * @author newcityman * @date 2019/8/14 - 22:13 */public class JDBCUtils {private static String url; private static String user; private static String password; private static String driver; static {try {// 读取资源文件,获取值// 1、创建properties集合类 Properties prop = new Properties();// 获取src路径下的文件的方式--->ClassLoader类加载器 ClassLoader classLoader = JDBCUtils.class.getClassLoader(); URL res = classLoader.getResource("jdbc.properties"); String path = res.getPath(); System.out.println(path);// 2、加载文件// prop.load(new FileReader("src/jdbc.properties")); prop.load(new FileReader(path));// 3、 获取数据,赋值 url = prop.getProperty("url"); user = prop.getProperty("user"); password = prop.getProperty("password"); driver = prop.getProperty("driver");// 4、注册驱动 try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } }// 获取连接 public static Connection getConnection() throws SQLException{return DriverManager.getConnection(url,user,password); }// 释放资源 public static void close(Statement stmt, Connection conn) {if (stmt != null) {try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } }if (conn != null) {try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }public static void close(ResultSet rs, Statement stmt, Connection conn) {if (rs != null) {try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } }if (stmt != null) {try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } }if (conn != null) {try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }}  

转载于:https://www.cnblogs.com/newcityboy/p/11355487.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)