mysql - execute multiple commands in java statement -
trying execute insert last id value select statement fails, works when throw mysql workbench works fine. 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 table_listnames (name) values ('alex'); select last_insert_id() 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 database!", e); } { system.out.println("closing connection."); if (connection != null) try { connection.close(); } catch (sqlexception ignore) {} }
an exececuteupdate whill never return 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 query new record. can try: getgeneratedkeys
but it's long time ago used plain java.sql doesn't know how handelt that. why u doesn't use hibernate. inserted entity wil automaticly id set after transaction end.
Comments
Post a Comment