Dbutil封裝類實現對MySQL數據庫的增刪改查及分頁


db.properties配置文件
代碼如下

db.driver=com.mysql.cj.jdbc.Driver db.url=jdbc:mysql://localhost:3306/db?serverTimezone=PRC&useSSL=false&useUnicode=true&characterEncoding=utf8 db.username=root db.password=



package
com; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.*; public class Newdbutil { private String driver; private String url; private String username; private String password; private String dbname; private Connection conn; private int recordcount; //總記錄條數 private int currpage = 1;//當前頁 private int pagesize = 10;//每頁記錄條數 private int pagecount = 1;//總頁數 /** * 初始化方法,完成配置文件的讀取(driver,URL,username,password) */ public void init() { Properties prop = new Properties(); InputStream is =this.getclass().getClassLoader().getResourceAsStream("db.properties"); try { prop.load(is); this.driver = prop.getProperty("db.driver"); this.url = prop.getProperty("db.url"); this.username = prop.getProperty("db.username"); this.password = prop.getProperty("db.password"); is.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 無參構造方法鏈接數據庫中的test庫 */ public Newdbutil() { this.init(); try { Class.forName(this.driver); try { this.conn = DriverManager.getConnection(this.url, this.username, this.password); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * <p>功能:實現數據插入操作</p> * * @param sql 數據庫預處理語句,實現插入數據功能 * @param objs 根據預處理語句填寫對應內容,有多少個問號就填幾個 * @return */ public int save(String sql, Object... objs) { int result = 0; try { PreparedStatement pst = this.conn.prepareStatement(sql); for (int i = 0; i < objs.length; i++) { pst.setObject(i + 1, objs[i]); } result = pst.executeUpdate(); pst.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * <p>功能:實現數據插入操作</p> * * @param sql 數據庫預處理語句,實現插入數據功能 * @param values 根據預處理語句填寫對應內容,有多少個問號數組中就填幾個值 * @return */ public int add(String sql, Object[] values) { int result = 0; try { PreparedStatement pst = this.conn.prepareStatement(sql); int indes = 1; for (Object obj : values) { pst.setObject(indes++, obj); } result = pst.executeUpdate(); pst.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * @param tablename 表名 * @param values map集合,key為表的列名,values為添加的值。 * @return */ public int insert(String tablename, Map<String, Object> values) { int result = 0; StringBuilder f = new StringBuilder(values.size()); StringBuilder v = new StringBuilder(values.size()); Set<String> kset = values.keySet(); for (String key : kset) { f.append(key + ","); v.append("?,"); } String sql = String.format("insert into %s(%s) values(%s)", tablename, f.substring(0, f.length() - 1), v.substring(0, v.length() - 1)); try { PreparedStatement pst = this.conn.prepareStatement(sql); int index = 1; for (String key : kset) { pst.setObject(index++, values.get(key)); } result = pst.executeUpdate(); pst.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * 功能:返回一個表的主鍵名 * * @param tablename * @return */ public String getPk(String tablename) { String pk = null; DatabaseMetaData dbmd; try { dbmd = this.conn.getMetaData(); ResultSet rs = dbmd.getPrimaryKeys(this.dbname, null, tablename); if (rs.next()) { pk = rs.getString(4); } } catch (SQLException e) { e.printStackTrace(); } return pk; } /** * 功能:根據主鍵刪除一條記錄 * * @param tablename 表名 * @param primarykey 要刪除記錄的主鍵名 * @return */ public int delete(String tablename, Object primarykey) { int result = 0; String sql = String.format("delete from %s where %s = ?", tablename, getPk(tablename)); try { PreparedStatement pst = this.conn.prepareStatement(sql); pst.setObject(1, primarykey); result = pst.executeUpdate(); pst.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * @param tablename * @param where 表示刪除條件一個條件一個問號 * @param objs 根據預處理語句填寫對應內容,有多少個問號就填幾個 * @return */ public int delete(String tablename, String where, Object... objs) { int result = 0; String sql = String.format("delete from %s %s", tablename, where); try { PreparedStatement pst = this.conn.prepareStatement(sql); for (int i = 0; i < objs.length; i++) { pst.setObject(i + 1, objs[i]); } result = pst.executeUpdate(); pst.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * @param sql update tablename set name = ? ... where id = ?, * @param objs "andy",...,100 根據update語句填寫共有幾個值 * @return */ public int update(String sql, Object... objs) { int result = 0; try { PreparedStatement pst = this.conn.prepareStatement(sql); for (int i = 0; i < objs.length; i++) { pst.setObject(i + 1, objs[i]); } } catch (SQLException e) { e.printStackTrace(); } return result; } /** * @param tablename 表名 * @param m map集合存放要修改的列名及值 * @param where 修改的條件 * @return */ public int update(String tablename, Map<String, Object> m, String where) { int result = 0; StringBuilder s = new StringBuilder(); for (String k : m.keySet()) { s.append(k + "=?,"); } String sql = String.format("update %s set %s %s", tablename, s.toString().substring(0, s.length() - 1), where); try { PreparedStatement pst = this.conn.prepareStatement(sql); int i = 0; for (Object o : m.values()) { pst.setObject(++i, o); } result = pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * 功能實現修改數據 * * @param tablename 表名 * @param map map集合存放要修改的列名及值,和表的主鍵名和主鍵值 * @return */ public int update(String tablename, Map<String, Object> map) { int result = 0; String pk = getPk(tablename); if (map.containsKey(pk)) { StringBuilder f = new StringBuilder(map.size()); Object pkname = map.get(pk); map.remove(pk); Set<String> kset = map.keySet(); for (String key : kset) { f.append(key + "=?,"); } String sql = String.format("update %s set %s where %s=?", tablename, f.substring(0, f.length() - 1), pk); try { PreparedStatement pst = this.conn.prepareStatement(sql); int index = 1; for (String key : kset) { pst.setObject(index++, map.get(key)); } pst.setObject(index, pkname); result = pst.executeUpdate(); pst.close(); } catch (SQLException e) { e.printStackTrace(); } } return result; } /** * 功能:實現表的查詢工作 只能查詢一條結果 * * @param sql sql查詢語句// select score name from stu where id = ?,1 * @param params 條件 * @return */ public Map<String, Object> queryone(String sql, Object... params) { Map<String, Object> map = null; try { PreparedStatement pst = this.conn.prepareStatement(sql); for (int i = 0; i < params.length; i++) { pst.setObject(i + 1, params[i]); } ResultSet rs = pst.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); String[] keys = new String[rsmd.getColumnCount()]; for (int c = 1; c <= rsmd.getColumnCount(); c++) { keys[c - 1] = rsmd.getColumnLabel(c); } map = new HashMap<String, Object>(); rs.next(); for (int n = 0; n < keys.length; n++) { map.put(keys[n], rs.getObject(keys[n])); } } catch (SQLException e) { e.printStackTrace(); } return map; } /** * 功能:實現表的查詢工作 能查詢多條結果,返回List<Map<String,Object>>集合。一條結果就是一個map。 * * @param sql sql查詢語句// select score name from stu where id = ?,1 * @param objs 條件 * @return */ public List<Map<String, Object>> query(String sql, Object... objs) { List<Map<String, Object>> list = null; try { PreparedStatement pst = this.conn.prepareStatement(sql); for (int i = 0; i < objs.length; i++) { pst.setObject(i + 1, objs[i]); } ResultSet rs = pst.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); String[] keys = new String[rsmd.getColumnCount()]; for (int m = 1; m <= rsmd.getColumnCount(); m++) { keys[m - 1] = rsmd.getColumnLabel(m); } list = new ArrayList<Map<String, Object>>(); while (rs.next()) { Map<String, Object> map = new HashMap<String, Object>(); for (int n = 0; n < keys.length; n++) { map.put(keys[n], rs.getObject(keys[n])); } list.add(map); } } catch (SQLException e) { e.printStackTrace(); } return list; } /** 實現分頁查詢與多條查詢類似 * @param sql select * from stu where id>?,1 * @param objs 條件 * @return */ public List<Map<String, Object>> page(String sql, Object... objs) { List<Map<String, Object>> list = null; String ccc = "select count(*)" + sql.substring(sql.indexOf("from")); try { PreparedStatement pst = this.conn.prepareStatement(ccc); int index = 1; for (Object o : objs) { pst.setObject(index++, o); } ResultSet rs = pst.executeQuery(); rs.next(); this.recordcount = rs.getInt(1);//總記錄條數 this.pagecount = this.recordcount % this.pagesize == 0 ? this.recordcount / this.pagesize : this.recordcount / this.pagesize + 1; if (this.currpage < 1) this.currpage = 1; if (this.currpage > getPagecount()) this.currpage = this.pagecount; String psql = sql + " limit ?,?"; pst = this.conn.prepareStatement(psql); index = 1; for (Object o : objs) { pst.setObject(index++, o); } pst.setInt(index++, this.currpage * this.pagesize - this.pagesize); pst.setInt(index, this.pagesize); rs = pst.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); list = new ArrayList<Map<String, Object>>(); while (rs.next()) { Map<String, Object> m = new HashMap<String, Object>(); int cc = rsmd.getColumnCount(); for (int i = 1; i <= cc; i++) { String name = rsmd.getColumnLabel(i); m.put(name, rs.getObject(name)); } list.add(m); } } catch (SQLException e) { e.printStackTrace(); } return list; } /** * 實現分頁查詢功能 * @param currpage 當前頁(查詢的第幾頁) * @param pagesize 每頁的記錄條數 * @param tablename 表名 * @param fields 查詢的對象(列名) * @param where 查詢的條件 * @return */ public List<Map<String, Object>> page(int currpage, int pagesize, String tablename, String fields, String where) { this.currpage = currpage; this.pagesize = pagesize; String sql = String.format("select %s from %s %s", fields, tablename, where); return page(sql); } public int getRecordcount() { return recordcount; } public void setRecordcount(int recordcount) { this.recordcount = recordcount; } public int getCurrpage() { return currpage; } public void setCurrpage(int currpage) { this.currpage = currpage; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } public int getPagecount() { return pagecount; } public void setPagecount(int pagecount) { this.pagecount = pagecount; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDbname() { return dbname; } public void setDbname(String dbname) { this.dbname = dbname; } public Connection getConn() { return conn; } public void setConn(Connection conn) { this.conn = conn; } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM