Six steps of JDBC programming

Six steps of JDBC programming:
    import the ojdbc file in the preparation work, then right-click to select the add path
    build path--> add oracle's ojdbc.jar package to the oracle installation directory
    (1). Register the driver
        Class.forName("oracle.jdbc .OracleDriver");
    (2).Connect to the database
        String url = "jdbc:oracle:thin:@localhost:1521:xe";//Where xe is sid
        String user = "XXX";
        String password = "XXX";
        Connection conn = DriverManager.getConnection(url,name,password);
    (3).Create a porter statement
        Statement state = conn.createStatement();
    (4).Move data, execute SQL statement
        String sql = "select id,name from s_emp "; //"insert into s_emp(id,name) values(12,'zhangsan')";
        ResultSet rs = state.executeQuery(sql);
    (5). Processing the result set
        while(rs.next()){
            int id = rs.getInt("id");
            String name = rs.getString(2);
            System.out.println(id+" "+name);
        }
    (6).关闭连接
        rs.close();
        state.close();
        conn.close();

The code as shown below implements the insert operation

[java]  view plain copy  
  1. publicvoid test_insert()    
  2. {  
  3.     String driver="oracle.jdbc.driver.OracleDriver";  
  4.     String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl";//orcl为sid  
  5.     String user="briup";  
  6.     String password="briup";  
  7.     Connection conn=;  
  8.      Statement stat=;  
  9.     try {  
  10.         //1, register the driver  
  11.         Class.forName(driver);  
  12.         //2, get the connection  
  13.          conn= DriverManager.getConnection(url, user, password);  
  14.          //System.out.println(conn);  
  15.         //3, create a statement object  
  16.         stat=conn.createStatement();  
  17.          //4, execute the sql statement  
  18.          String sql="insert into lover values(5,'suxingxing',to_date('21-9-2016','dd-mm-yyyy'))";  
  19.          stat.execute(sql);  
  20.          //System.out.println(stat.execute(sql));  
  21.          //5. Process the result set, if there is one, process it, if not, do not need to process it. Of course, the insert statement does not need to be processed.  
  22.     } catch (Exception e) {  
  23.         e.printStackTrace ();  
  24.     }  
  25.     finally{  
  26.         //6, close the resource  
  27.         try {  
  28.             if(stat!=)stat.close();  
  29.         } catch (SQLException e) {  
  30.             e.printStackTrace ();  
  31.         }  
  32.         try {  
  33.             if(conn!=)conn.close();  
  34.         } catch (SQLException e) {  
  35.             e.printStackTrace ();  
  36.         }  
  37.     }  
  38. }  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325855219&siteId=291194637