Re: Problems with getGeneratedKeys();
Posted by: Tetsuro Ikeda
Date: May 31, 2005 01:41AM

Hi Isabelle,

> I try to get the primarykey, which is auto
> incremented, after an executeUpdate, but the
> ResultSet is empty although the row is well
> included.
> I don't understand why.
> Could someone help me please ...

See this trivial sample. (I re-edited the previous post in some code)

<code>
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost/test";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(url, "", "");
Statement stmt = conn.createStatement();
ResultSet rs = null;
stmt.executeUpdate("DROP TABLE IF EXISTS t1");
stmt.executeUpdate("CREATE TABLE t1 (c1 int primary key auto_increment, c2 char(2))");
stmt.executeUpdate("INSERT INTO t1 (c2) values('a')");
rs = stmt.getGeneratedKeys();
rs.next();
System.out.println("key=" + rs.getInt("GENERATED_KEY"));
stmt.executeUpdate("UPDATE t1 SET c2='aa' WHERE c2='a'");
stmt.executeUpdate("INSERT INTO t1 (c2) values('b')");
rs = stmt.getGeneratedKeys();
rs.next();
System.out.println("key=" + rs.getInt(1));

rs = stmt.executeQuery("SELECT * FROM t1");
while (rs.next()) {
System.out.println("c1=" + rs.getInt("c1") + ", c2=" + rs.getString("c2"));
}
stmt.close();
conn.close();
}
</code>

<stdout>
key=1
key=2
c1=1, c2=aa
c1=2, c2=b
</stdout>



Edited 1 time(s). Last edit at 05/31/2005 03:09AM by Tetsuro Ikeda.

Options: ReplyQuote


Subject
Written By
Posted
Re: Problems with getGeneratedKeys();
May 31, 2005 01:41AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.