[英]How to execute composite sql queries in java?
如何執行以下查詢並通過准備好的語句檢索結果:
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'); SELECT LAST_INSERT_ID();”沒有問題直接從 mysql 控制台。
更新(插入)數據時使用executeUpdate
而不是executeQuery
。 嘗試執行SELECT LAST_INSERT_ID()
作為另一個查詢。
但它不是便攜式查詢。 我建議改用Statement.getGeneratedKeys
。 請看這里: 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
}
}
}
這里與 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
}
}
}
正如其他人已經說過的那樣,這行不通。 但看起來您只想獲取最后插入的 ID。 為此,您可以使用Statement
class 的getGeneratedKeys()
方法。
嘗試:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.