您好,登錄后才能下訂單哦!
url=jdbc:mysql://localhost:3306/testdb user=root password=root driverClass=com.mysql.jdbc.Driver
package com.rk.db.utils; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * JDBC的工具類 * @author RK * */ public class JDBCUtil { private static final String url; private static final String user; private static final String password; private static final String driverClass; /** * 靜態(tài)代碼塊中(只加載一次) */ static { try { //讀取db.properties文件 InputStream inStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties"); Properties props = new Properties(); //加載文件 props.load(inStream); //讀取信息 url = props.getProperty("url"); user = props.getProperty("user"); password = props.getProperty("password"); driverClass = props.getProperty("driverClass"); //注冊驅(qū)動程序 Class.forName(driverClass); } catch (IOException e) { System.out.println("讀取數(shù)據(jù)庫配置文件出錯"); throw new RuntimeException(e); } catch (ClassNotFoundException e) { System.out.println("數(shù)據(jù)庫驅(qū)程程序注冊出錯"); throw new RuntimeException(e); } } /** * 獲取數(shù)據(jù)庫的連接 * @return 數(shù)據(jù)庫連接 */ public static Connection getConnection() { try { return DriverManager.getConnection(url,user,password); } catch (SQLException e) { System.out.println("獲取數(shù)據(jù)庫連接出錯"); throw new RuntimeException(e); } } /** * 關(guān)閉Connection、Statement和ResultSet * @param conn 數(shù)據(jù)庫連接 * @param stmt 執(zhí)行SQL語句的命令 * @param rs 結(jié)果集 */ public static void close(Connection conn,Statement stmt,ResultSet rs) { closeQuietly(rs); closeQuietly(stmt); closeQuietly(conn); } /** * 安靜的關(guān)閉數(shù)據(jù)庫資源 * @param ac 實現(xiàn)了AutoCloseable接口的對象 */ public static void closeQuietly(AutoCloseable ac) { if(ac != null) { try { ac.close(); } catch (Exception e) { e.printStackTrace(); } } } }
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。