2011-07-21 51 views
2

我如何執行下面的查詢和檢索通過事先準備好的聲明的結果:如何在java中執行復合sql查詢?

INSERT INTO vcVisitors (sid) VALUES (?); SELECT LAST_INSERT_ID(); 

有一次同時執行兩個語句的方法嗎?

我試着做到以下幾點:

Connection con = DbManager.getConnection(); 
PreparedStatement ps = con.PrepareStatement(
    "INSERT INTO vcVisitors (sid) VALUES (?); SELECT LAST_INSERT_ID();"); 
ps.setInt(1, 10); 
ResultSet rs = ps.exequteQuery(); 
rs.next(); 
return rs.getInt("LAST_INSERT_ID()"); 

,但它給了我一個錯誤的executeQuery不能執行這樣的查詢, 我也試着通過更換的executeQuery以下:

ps.execute(); 
rs = ps.getResultSet(); 

,但它給我的SQL語法錯誤:

You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version 
for the right syntax to use near 'SELECT LAST_INSERT_ID()' at line 1 

但執行查詢時沒有問題 「INSERT INTO vcVisitors(sid)VALUES('10');直接從MySQL控制檯「

+0

我不認爲這是可能的。特別是不用'INSERT'和'SELECT'。 – Jacob

回答

2

在更新(插入)數據使用executeUpdate代替executeQuery嘗試執行SELECT LAST_INSERT_ID()作爲另一個查詢

但它是不可移植的查詢我建議使用Statement.getGeneratedKeys; SELECT LAST_INSERT_ID()。而是請看這裏:JDBC (MySQL) Retrieving AUTO_INCREMENT Column Values

下面是正確使用LAST_INSERT_ID()的例子:

Statement stmt = null; 
    ResultSet rs = null; 

    try { 

    // 
    // Create a Statement instance that we can use for 
    // 'normal' result sets. 

    stmt = conn.createStatement(); 

    // 
    // Issue the DDL queries for the table for this example 
    // 

    stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial"); 
    stmt.executeUpdate(
      "CREATE TABLE autoIncTutorial (" 
      + "priKey INT NOT NULL AUTO_INCREMENT, " 
      + "dataField VARCHAR(64), PRIMARY KEY (priKey))"); 

    // 
    // Insert one row that will generate an AUTO INCREMENT 
    // key in the 'priKey' field 
    // 

    stmt.executeUpdate(
      "INSERT INTO autoIncTutorial (dataField) " 
      + "values ('Can I Get the Auto Increment Field?')"); 

    // 
    // Use the MySQL LAST_INSERT_ID() 
    // function to do the same thing as getGeneratedKeys() 
    // 

    int autoIncKeyFromFunc = -1; 
    rs = stmt.executeQuery("SELECT LAST_INSERT_ID()"); 

    if (rs.next()) { 
     autoIncKeyFromFunc = rs.getInt(1); 
    } else { 
     // throw an exception from here 
    } 

    rs.close(); 

    System.out.println("Key returned from " + 
         "'SELECT LAST_INSERT_ID()': " + 
         autoIncKeyFromFunc); 

} finally { 

    if (rs != null) { 
     try { 
      rs.close(); 
     } catch (SQLException ex) { 
      // ignore 
     } 
    } 

    if (stmt != null) { 
     try { 
      stmt.close(); 
     } catch (SQLException ex) { 
      // ignore 
     } 
    } 
} 

的d這裏的getGeneratedKeys相同:

 Statement stmt = null; 
    ResultSet rs = null; 

    try { 

    // 
    // Create a Statement instance that we can use for 
    // 'normal' result sets assuming you have a 
    // Connection 'conn' to a MySQL database already 
    // available 

    stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, 
           java.sql.ResultSet.CONCUR_UPDATABLE); 

    // 
    // Issue the DDL queries for the table for this example 
    // 

    stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial"); 
    stmt.executeUpdate(
      "CREATE TABLE autoIncTutorial (" 
      + "priKey INT NOT NULL AUTO_INCREMENT, " 
      + "dataField VARCHAR(64), PRIMARY KEY (priKey))"); 

    // 
    // Insert one row that will generate an AUTO INCREMENT 
    // key in the 'priKey' field 
    // 

    stmt.executeUpdate(
      "INSERT INTO autoIncTutorial (dataField) " 
      + "values ('Can I Get the Auto Increment Field?')", 
      Statement.RETURN_GENERATED_KEYS); 

    // 
    // Example of using Statement.getGeneratedKeys() 
    // to retrieve the value of an auto-increment 
    // value 
    // 

    int autoIncKeyFromApi = -1; 

    rs = stmt.getGeneratedKeys(); 

    if (rs.next()) { 
     autoIncKeyFromApi = rs.getInt(1); 
    } else { 

     // throw an exception from here 
    } 

    rs.close(); 

    rs = null; 

    System.out.println("Key returned from getGeneratedKeys():" 
     + autoIncKeyFromApi); 
} finally { 

    if (rs != null) { 
     try { 
      rs.close(); 
     } catch (SQLException ex) { 
      // ignore 
     } 
    } 

    if (stmt != null) { 
     try { 
      stmt.close(); 
     } catch (SQLException ex) { 
      // ignore 
     } 
    } 
} 
+0

他特別希望一次執行兩個查詢。 – Jacob

+1

用於顯示getGeneratedKeys()的用法+1() –

1

嘗試用:

Connection con = DbManager.getConnection(); 
int lastid = 0; 

PreparedStatement psInsert = con.PrepareStatement(
    "INSERT INTO vcVisitors (sid) VALUES (?)"); 
psInsert.setInt(1, 10); 
psInsert.executeUpdate(); 

PreparedStatement psSelect = 
    con.PrepareStatement("SELECT LAST_INSERT_ID() AS lastid"); 
ResultSet rs = psSelect.executeQuery(); 
rs.next(); 

lastid = rs.getInt("lastid"); 

rs.close(); 
psInsert.close(); 
psSelect.close(); 
con.close(); 
return lastid; 
+0

是的,肯定有效,但我的問題是如何一次執行多個查詢 – tsds

+0

@tsds:但是兩個查詢總是作爲兩個查詢運行。 – Jonas

2

正如其他人已經說過了,這是不行的。但它看起來像你只想得到最後一個插入的ID。爲了達到這個目的,你可以使用Statement類的getGeneratedKeys()方法。