尝试执行插入操作,然后获取最后一个id值,但是我得到的结果是select语句失败,但它在我将它放入mysql工作台时工作正常。什么是Java代码失败?在java语句中执行多个命令
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
import java.sql.Statement
import java.sql.ResultSet
String url = "jdbc:mysql://localhost:3306/";
String user = "root"
String password = "password"
Connection connection = null;
try {
System.out.println("Connecting database...");
connection = DriverManager.getConnection(url,user,password);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeUpdate("INSERT INTO table_listnames (name) VALUES ('alex'); SELECT LAST_INSERT_ID() as lastId;");
while (rs.next()) {
String lastId = rs.getString("lastId");
println(lastId)
}
println("closing now")
stmt.close()
connection.close()
} catch (SQLException e) {
throw new RuntimeException("Cannot connect the database!", e);
} finally {
System.out.println("Closing the connection.");
if (connection != null) try {
connection.close();
} catch (SQLException ignore) {}
}
更大图片溶液:http://stackoverflow.com/questions/1915166/how-to-get-the-insert-id-in-jdbc –