2011-07-21 4 views
2

は、どのように私は次のクエリを実行し、プリペアドステートメントを経由して結果を取得することができます。javaで複合SQLクエリを実行するには?

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

は一度に両方の二つの文を実行する方法はありますか?私もでのexecuteQueryを交換しようとした

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は、このようなクエリを実行することができないというエラーを与え、 :私は次の操作を実行しようとした

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'); LAST_INSERT_ID()を選択します。。。。mysqlのコンソールから直接」

+0

私はそれが可能だとは思わない。特に 'INSERT'と' SELECT'ではありません。 – Jacob

答えて

2

(挿入)データの更新中は

別のクエリとして SELECT LAST_INSERT_ID()を実行してみ executeUpdateの代わり executeQueryを使用ししかし、それは、ポータブルクエリではありません、私は Statement.getGeneratedKeysを使用してお勧めします。 。代わりに、こちらをご覧ください:。

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 
     } 
    } 
} 

JDBC (MySQL) Retrieving AUTO_INCREMENT Column Valuesここ

は、適切に使用LAST_INSERT_ID()の一例ですここで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

+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:しかし、2つのクエリは常に2つのクエリとして実行されます。 – Jonas

2

他の人がすでに述べたように、これは動作しません。しかし、あなたはちょうど最後の挿入物のIDを取得するように見えます。これを実現するには、StatementクラスのgetGeneratedKeys()メソッドを使用できます。

関連する問題