java操作數(shù)據(jù)庫, 如果不進(jìn)行整合, 添加,刪除,修改,查詢等操作將會有太多的重復(fù)代碼出現(xiàn), 操作不易, 同時也影響美觀, 因此,將重復(fù)的代碼進(jìn)行整合,形成一個類, 然后調(diào)用就會簡單很多
package yteng; //先在lib下引入包mysql-connector-java-5.1.39-bin.jar import java.sql.*; public class Db { // MySQL 8.0 以下版本 - JDBC 驅(qū)動名及數(shù)據(jù)庫 URL static final String DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/stu_info"; // MySQL 8.0 以上版本 - JDBC 驅(qū)動名及數(shù)據(jù)庫 URL //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; //static final String DB_URL = "jdbc:mysql://localhost:3306/stu_info?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"; static final String USER = "root"; static final String PASS = "root"; public static Connection conn = null; public static PreparedStatement ps = null; public static ResultSet rs = null; static { try { //加載驅(qū)動 Class.forName(DRIVER); //將mysql驅(qū)動注冊到DriverManager中去 //Class.forName 方法的作用,就是初始化給定的類 } catch(ClassNotFoundException e) { System.out.println(e.getMessage()); } } //得到數(shù)據(jù)庫連接對象 public static Connection conn() { if(conn == null){ //獲取連接 try { conn = DriverManager.getConnection(DB_URL,USER,PASS); } catch (SQLException e) { e.printStackTrace(); } //返回一個數(shù)據(jù)庫連接對象, 通過個對象就可以對數(shù)據(jù)庫進(jìn)行增刪除改查操作了 } return conn; } //基本的增,刪,改操作 public static int exec(String sql, Object...args) { conn = conn(); int count = 0; try { //prepareStatement對象防止sql注入的方式是把用戶非法輸入的單引號用\反斜杠做了轉(zhuǎn)義,從而達(dá)到了防止sql注入的目的 ps = conn.prepareStatement(sql); //設(shè)置占位符參數(shù) if(args != null) { for(int i = 0; i < args.length; i++) { ps.setObject(i+1, args[i]); } } count = ps.executeUpdate(); //設(shè)置占位符參數(shù) } catch(SQLException e) { System.out.println(e.getMessage()); } return count; } //返回新增加數(shù)據(jù)的id public static int lastInsertId(String sql, Object...args) { conn = conn(); int id = -1; try { //prepareStatement對象防止sql注入的方式是把用戶非法輸入的單引號用\反斜杠做了轉(zhuǎn)義,從而達(dá)到了防止sql注入的目的 ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); //設(shè)置占位符參數(shù) if(args != null) { for(int i = 0; i < args.length; i++) { ps.setObject(i+1, args[i]); } } ps.executeUpdate(); rs = ps.getGeneratedKeys(); if(rs.next()) { id = rs.getInt(1); } //設(shè)置占位符參數(shù) } catch(SQLException e) { System.out.println(e.getMessage()); } return id; } //查詢操作 public static ResultSet fetch(String sql, Object...args) { conn = conn(); try { ps = conn.prepareStatement(sql); //設(shè)置占位符參數(shù) if(args != null) { for(int i = 0; i < args.length; i++) { ps.setObject(i+1, args[i]); } } rs = ps.executeQuery(); //返回 查詢的數(shù)據(jù)結(jié)果 //設(shè)置占位符參數(shù) } catch(SQLException e) { System.out.println(e.getMessage()); } return rs; } public static void close() { try { if(rs != null) {rs.close(); rs = null;} if(ps != null) {ps.close(); ps = null;} if(conn != null) {conn.close(); conn = null;} } catch(SQLException e) { System.out.println(e.getMessage()); } } }
Db.java下載