简体   繁体   中英

execute multiple commands in java statement

Trying to execute an insert then get the last id value but I get that the select statement fails, however it works when I throw it into mysql workbench it works fine. What is the java code failing?

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

An exececuteUpdate whill never return a ResultSet. See:

int executeUpdate(String sql) throws SQLException

http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)

You have to query for your new record. You can try: getGeneratedKeys

But it's so long time ago I used plain java.sql i doesn't know how we handelt that. Why u doesn't use something like hibernate. An inserted entity wil automaticly get his id set after transaction end.

Yeah, this is your problem:

ResultSet rs = stmt.executeUpdate("INSERT INTO table_listnames (name) VALUES ('alex'); SELECT LAST_INSERT_ID() as lastId;");

Your SELECT statement isn't an update. But the JDBC call you're making is to do an UPDATE.

Split it into two calls. Do the SELECT separately.

And don't forget to close your ResultSet objects (perhaps in the finally block).

Here is some code I wrote in a DAO to add a word with a wordID into a database table using JDBC it illustrates how to add a row into a table get the generated key. The first column in the word table is an INT (which gets autogenerated by the database when null), the second column is a VARCHAR containing the supplied word. The Word class (not shown) is just a trivial class to encapsulate the wordID integer and a String with getters and setters.

Although it is a little more complex than your question as it contains JNDI and prepared statements as well, this code should get you started.

/** Attempts to add a Word. Returning a clone of the word including the wordID on success */ static final Word createWord(final Word word) throws Exception {
InitialContext initialContext = null; DataSource ds = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null;

  try{ initialContext = new InitialContext(); ds = (DataSource) initialContext.lookup( "java:/comp/env/jdbc/MyDatabase" ); conn = ds.getConnection(); if(word.getWordID() == 0) { stmt = conn.prepareStatement("INSERT INTO words VALUES(?,?)", Statement.RETURN_GENERATED_KEYS); stmt.setNull(1, Types.INTEGER); //wordID stmt.setString(2, word.getText()); // execute the insert and get the new wordID int rowsAdded = stmt.executeUpdate(); if(rowsAdded == 0)return null; Integer key = null; rs = stmt.getGeneratedKeys(); if(rs.next()){key = new Integer(rs.getInt("GENERATED_KEY"));} rs.close(); // clone the word but add in the word id Word retval = new Word(word.getText()); retval.setWordID(key); return retval; } return null; } catch(NamingException e) { throw new Exception("WordDAO: failed to obtain DataSource", e); } catch (SQLException e) { e.printStackTrace(); if(Log.isLogError())Log.error("WordDAO: SQLException" + e.getMessage(), e); return null; } finally { // Always make sure result sets and statements are closed and the connection is returned to the pool if (rs != null){try{rs.close();}catch (SQLException e){}rs = null;} if (stmt != null){try{stmt.close();}catch(SQLException e){}stmt = null;} if (conn != null){try {conn.close();}catch(SQLException e){}conn = null;} } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM