JDBC刪除數據sql
Demo: 刪除數據 (刪除編號是 7369 的僱員信息)app
1 public class TestMysql { 2 //取得鏈接 3 private static Connection conn =ConnectionUitl.getConnection(); 4 5 public static void main(String[] args) { 6 System.out.println("刪除的數據行數是:" + deleteById(7369)); 7 } 8 9 public static int deleteById(Integer empno) { 10 String sql = "DELETE FROM emp WHERE empno=" + empno; 11 12 //獲取發送 sql 語句的對象 13 try { 14 PreparedStatement pst = conn.prepareStatement(sql); 15 //發送 sql 語句 16 return pst.executeUpdate(); 17 } catch (Exception e) { 18 e.printStackTrace(); 19 } finally { 20 ConnectionUitl.close(conn); 21 } 22 return 0; 23 } 24 }
Demo: 批量刪除數據 (刪除編號爲 7654/7782/7844 的僱員信息)
方法: 能夠把要刪除的僱員的編號保存到一個集合中傳遞這個方法進行刪除ui
1 public class TestMysql { 2 //取得鏈接 3 private static Connection conn =ConnectionUitl.getConnection(); 4 5 public static void main(String[] args) { 6 Set<Integer> empnos = new HashSet<Integer>(); 7 empnos.add(7654); 8 empnos.add(7782); 9 empnos.add(7844); 10 System.out.println("刪除的數據行數是: " + deleteBarch(empnos)); 11 } 12 13 public static int deleteBarch(Set<Integer> empnos) { 14 StringBuffer sb = new StringBuffer("DELETE FROM emp WHERE empno IN("); 15 Iterator<Integer> iter = empnos.iterator(); 16 while (iter.hasNext()) { 17 sb.append(iter.next() + ","); 18 } 19 20 sb.delete(sb.length()-1, sb.length()); 21 sb.append(")"); 22 23 24 //獲取發送 sql 語句的對象 25 try { 26 PreparedStatement pst = conn.prepareStatement(sb.toString()); 27 //執行 sql 語句 28 return pst.executeUpdate(); 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } finally { 32 ConnectionUitl.close(conn); 33 } 34 return 0; 35 } 36 }
爲何使用StringBuffer 而不是String
由於自渡船要頻繁的修改,若是使用 String 會形成大量垃圾
(String 類型一旦聲明則內容不能夠改變, 改變的是引用, 引用會致使垃圾產生),
因此這種狀況下使用 StringBuffer 或者 StringBuilder.spa