java之jdbc_採用PreparedStatement刪除數據

動力節點筆記java

 

  
  
  
  
  1. import java.sql.*;  
  2. import java.text.*;  
  3. import java.util.*;  
  4. //採用PreparedStatement刪除數據  
  5. public class DeleteTest02 {  
  6.     public static void main(String[] args) {  
  7.         if (args.length != 1) {  
  8.             throw new IllegalArgumentException("參數非法,正確使用爲InsertTest01 ...");     
  9.         }  
  10.           
  11.         Connection conn = null;  
  12.         PreparedStatement pstmt = null;  
  13.         try {  
  14.             //第一步,加載數據庫驅動,不一樣的數據庫驅動程序不同  
  15.             Class.forName("oracle.jdbc.driver.OracleDriver");  
  16.             //第二部,獲得數據庫鏈接  
  17.             String dburl = "jdbc:oracle:thin:@localhost:1521:orcl";  
  18.             //String dburl = "jdbc:oracle:thin:@192.168.21.1:1521:orcl";  
  19.             //String dburl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";  
  20.             String userName = "system";  
  21.             String password = "wanwan";  
  22.             conn = DriverManager.getConnection(dburl, userName, password);  
  23.             //System.out.println(conn);  
  24.                       
  25.             //取得輸入參數          
  26.             int empno = Integer.parseInt(args[0]);  
  27.       
  28.             //第三步,建立Statement,執行SQL語句  
  29.             //採用佔位符的方式  
  30.             //最好將比較複雜的sql調通,再將sql語句和程序相結合,進行連調  
  31.             String sql = "delete from enp where empno = ?";   
  32.               
  33.               
  34.               
  35.             pstmt = conn.prepareStatement(sql);  
  36.             //爲佔位符賦值  
  37.             pstmt.setInt(1, empno);  
  38.               
  39.             pstmt.executeUpdate();  
  40.               
  41.             System.out.println("刪除員工成功, 員工編號:【"+ empno +"】");  
  42.       
  43.         } catch (ClassNotFoundException e) {  
  44.             e.printStackTrace();  
  45.         } catch (SQLException e) {  
  46.             e.printStackTrace();  
  47.         } finally {  
  48.             //注意關閉原則:從裏到外  
  49.             try {  
  50.                 if (pstmt != null) {  
  51.                     pstmt.close();    
  52.                 }  
  53.                 if (conn != null) {  
  54.                     conn.close();  
  55.                 }  
  56.             } catch(SQLException e) {  
  57.                           
  58.             }  
  59.               
  60.         }  
  61.     }     
相關文章
相關標籤/搜索