java之jdbc_採用Statement添加數據

動力節點筆記java

 

  
  
  
  
  1. import java.sql.*;  
  2. //採用Statement添加數據  
  3. public class InsertTest01 {  
  4.     public static void main(String[] args) {  
  5.         if (args.length != 8) {  
  6.             throw new IllegalArgumentException("參數非法,正確使用爲InsertTest01 ...");     
  7.         }  
  8.           
  9.         Connection conn = null;  
  10.         Statement stmt = null;  
  11.         try {  
  12.             //第一步,加載數據庫驅動,不一樣的數據庫驅動程序不同  
  13.             Class.forName("oracle.jdbc.driver.OracleDriver");  
  14.             //第二部,獲得數據庫鏈接  
  15.             String dburl = "jdbc:oracle:thin:@localhost:1521:orcl";  
  16.             //String dburl = "jdbc:oracle:thin:@192.168.21.1:1521:orcl";  
  17.             //String dburl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";  
  18.             String userName = "system";  
  19.             String password = "wanwan";  
  20.             conn = DriverManager.getConnection(dburl, userName, password);  
  21.             //System.out.println(conn);  
  22.               
  23.               
  24.             int empno = Integer.parseInt(args[0]);  
  25.             String ename = args[1];  
  26.             String job = args[2];  
  27.             int mgr = Integer.parseInt(args[3]);  
  28.             //格式:yyyy-mm-dd  
  29.             String hiredate = args[4];  
  30.             float sal = Float.parseFloat(args[5]);  
  31.             float comm = Float.parseFloat(args[6]);  
  32.             int deptno = Integer.parseInt(args[7]);  
  33.               
  34.             //第三步,建立Statement,執行SQL語句  
  35.             //拼串  
  36.             //最好將比較複雜的sql調通,再將sql語句和程序相結合,進行連調  
  37.             String sql = "insert into enp(empno, ename, job, mgr, hiredate, sal, comm, deptno) ";  
  38.               
  39.             sql += "values("+ empno +", '"+ ename +"', '"+ job +"', "+ mgr +", ";  
  40.             sql += "to_date('"+ hiredate +"', 'yyyy-mm-dd'), "+ sal + ", "+ comm +", "+ deptno +")";  
  41.               
  42.             System.out.println("sql = " + sql);  
  43.             stmt = conn.createStatement();  
  44.             stmt.executeUpdate(sql);  
  45.             System.out.println("添加員工成功");  
  46.               
  47.               
  48.               
  49.         } catch (ClassNotFoundException e) {  
  50.             e.printStackTrace();  
  51.         } catch (SQLException e) {  
  52.             e.printStackTrace();  
  53.         } finally {  
  54.             //注意關閉原則:從裏到外  
  55.             try {  
  56.                 if (stmt != null) {  
  57.                     stmt.close();     
  58.                 }  
  59.                 if (conn != null) {  
  60.                     conn.close();  
  61.                 }  
  62.             } catch(SQLException e) {  
  63.                           
  64.             }  
  65.               
  66.         }  
  67.     }     
相關文章
相關標籤/搜索