2013-03-23 79 views
0

我正在編寫一個程序,它將接收一個學生ID並驗證該ID是否存在於一個mysql表中。如果它確實存在,我想將它存在的整個行並將該行復制到另一個表中。目前,該程序只是將表中的所有行復制到另一個表中。任何幫助讚賞。我在下面插入了一段代碼。從一個mysql表插入信息到另一個

try { 
    String compareText = IDField.getText().trim(); 

    if(compareText.length() > 0){ 
     Class.forName("com.mysql.jdbc.Driver"); 
     conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password"); 
     System.out.println("Connected to database"); 

     Statement stmt1  = conn.createStatement(); 
     ResultSet rs1  = stmt1.executeQuery("select * from students where LUID='"+IDField.getText()+"' "); 

     boolean isPresent = rs1.next(); 

     if (isPresent) 
     { 
      Class.forName("com.mysql.jdbc.Driver"); 
      conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password"); 
      System.out.println("Connected to database"); 

      int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students"); 

      if (rows == 0) 
      { 
       System.out.println("Don't add any row!"); 
      } 
      else 
      { 
       System.out.println(rows + " row(s)affected."); 
       conn.close(); 
      } 

      //System.out.println("Already exists!!"); 
     } 
+0

一舉兩得表駐留在同一個數據庫,或者是他們在不同的數據庫,如標題所暗示? – Geier 2013-03-23 18:58:04

+0

這兩個表都在同一個數據庫中。感謝您指出了這一點。 – user2188777 2013-03-23 18:59:03

回答

1

你可以都做在單個SQL語句:

INSERT INTO <Dest-Table> 
(SELECT * FROM <Src-Table> WHERE ID=?); 

它只會複製存在的行。

+0

謝謝。我會研究這種方法。 – user2188777 2013-03-23 19:34:41

0

我懷疑這是由於該行:

int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students"); 

爲,如果該行被解析,該SELECT語句沒有WHERE條款,因此將獲得每行,因此插入的一切。

+0

謝謝。我將研究WHERE子句。 – user2188777 2013-03-23 19:35:06

0

預處理語句

 String sql = "INSERT INTO abc" 
       + "(SELECT id1,id2 FROM pqr)"; 

     ps1 = con.prepareStatement(sql); 


     int rs = ps1.executeUpdate(); 

     if (rs > 0) { 

      update = true; 

     } else { 
      update = false; 
     } 

    } catch (Exception ex) { 

     ex.printStackTrace(); 
    } finally { 
     try { 
      if (ps1 != null) { 
       ps1.close(); 
       ps1 = null; 
      } 
      if (con != null) { 
       con.close(); 
       con = null; 
      } 
     } catch (Exception e) { 

     } 
    } 
    return update;