封裝 JDBC 工具類
阿新 • • 發佈:2021-12-10
JDBC 封裝
使用 JDBC 連線 MySQL 資料庫,我們每次操作都要寫一堆連線資料庫的資訊,操作完還要釋放一堆資源,做了很多重複的工作,於是我們通常把資料庫連線封裝成工具類。
JdbcUtils 類
import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import java.sql.*; /** * @author Acx7 */ public class JdbcUtils { private static String username = null; private static String password = null; private static String url = null; static { try { // 載入配置檔案 Properties properties = new Properties(); properties.load(new FileInputStream("resources/db.properties")); // 獲取配置檔案資訊 String driver = properties.getProperty("driver"); username = properties.getProperty("username"); password = properties.getProperty("password"); url = properties.getProperty("url"); // 載入驅動 Class.forName(driver); } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); } } /** * 獲取連線物件 */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, username, password); } /** * 釋放資源 */ public static void close(Statement ps, Connection conn) { close(null, ps, conn); } /** * 釋放資源 */ public static void close(ResultSet rs, Statement ps, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
配置檔案
driver=com.mysql.jdbc.Driver
username=root
password=123456
url=jdbc:mysql://127.0.0.1:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8
使用方法
import java.sql.*; //import JdbcUtils; /** * @author Acx7 */ public class JdbcTest { public static void main(String[] args) { Statement st = null; ResultSet rs = null; Connection conn = null; try { conn = JdbcUtils.getConnection(); st = conn.createStatement(); String sql = "SELECT * FROM users"; rs = st.executeQuery(sql); while (rs.next()) { System.out.println(rs.getObject("id")); } // String sql = "INSERT INTO users(id,`name`) VALUES (4,'Acx7')"; // int result = st.executeUpdate(sql); // 返回受影響的行數 // String sql = "UPDATE users SET `name`='acx' WHERE id=4"; // int result = st.executeUpdate(sql); // 返回受影響的行數 // String sql = "DELETE FROM users WHERE id=3"; // int result = st.executeUpdate(sql); // 返回受影響的行數 } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtils.close(rs, st, conn); } } }