Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / Databases / May 2008

Tip: Looking for answers? Try searching our database.

Getting a Mysql auto increment value back into my Java client GUI?

Thread view: 
BoBi - 19 Mar 2008 19:33 GMT
Hello,

I'm busy developing a Java GUI client/server database application with
Netbeans IDE 6.0 and
Mysql to automate the data management and other tasks for my Dongo
website
(see http://www.dongo.org to get an idea what is the targeted result
of all
my programming). I have a question as described below.

To insert a country in my mysql country table I use the code below
which is working fine:

 private static void countryInsert(Country country) {
   if (country.isValid())
   try {
     String sqlString = "INSERT INTO country VALUES(0, '" +
country.getCode();
     sqlString += "', '" + country.getName() + "')";
     sqlStatement.executeUpdate(sqlString);
   } catch (SQLException ex) {
     Logger.getLogger(Objectbase.class.getName()).log(Level.SEVERE,
null, ex);
   }
 }

The first column sid of the country table (as for all my tables) is
auto increment:

| sid   | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment

I would like to get the value assigned to sid by Mysql back into my
client Java application
preferably with the one sql statement I'm already using to insert.
Only if really necessary
with a second sql statement. What is the best way to programm this?

Thanks and best regards :c),

BoBi
David Harper - 19 Mar 2008 22:20 GMT
> Hello,
>
[quoted text clipped - 32 lines]
> Only if really necessary
> with a second sql statement. What is the best way to programm this?

The best solution is to use Connection.prepareStatement(String sql, int
autoGeneratedKeys) to create a prepared statement:

  String sqlString = "INSERT INTO country(countryCode,countryName)
   VALUES(?,?)";

  PreparedStatement pstmt = conn.prepareStatement(sqlString,
      Statement.RETURN_GENERATED_KEYS);

assuming that your table has columns named countryCode and countryName
to store the country code and name respectively.

Then insert a row using code such as

  pstmt.setString(1, country.getCode());
  pstmt.setString(2, country.getName());

  int rc = pstmt.executeUpdate();

  // rc is the number of rows actually inserted

and retrieve the auto_increment value generated by the server like this:

  ResultSet rs = pstmt.getGeneratedKeys();

  int sid = rs.next() ? rs.getInt(1) : -1;

  rs.close();

The use of a prepared statement is also preferable to hard-coding quotes
into an SQL query string as you did in your code snippet.

You can also re-use the prepared statement to insert further rows, for
as long as the parent connection remains open.  All in all, prepared
statements are a more elegant, flexible and secure approach, as well as
providing a convenient way to get auto_increment values.

David Harper
Cambridge, England
Lew - 20 Mar 2008 00:55 GMT
BoBi wrote:
>> I would like to get the value assigned to sid by Mysql back into my
>> client Java application
>> preferably with the one sql statement I'm already using to insert.
>> Only if really necessary
>> with a second sql statement. What is the best way to programm this?

> The best solution is to use Connection.prepareStatement(String sql, int
> autoGeneratedKeys) to create a prepared statement:
[quoted text clipped - 20 lines]
>
>   ResultSet rs = pstmt.getGeneratedKeys();

If only you were using PostgreSQL, you could use their extension to the INSERT
command:
  [ RETURNING * | output_expression [ AS output_name ] [, ...] ]

> The optional RETURNING clause causes INSERT to compute and return value(s)
> based on each row actually inserted. This is primarily useful for obtaining
> values that were supplied by defaults, such as a serial sequence number.
> However, any expression using the table's columns is allowed. The syntax of
> the RETURNING list is identical to that of the output list of SELECT.
<http://www.postgresql.org/docs/8.2/interactive/sql-insert.html>

Signature

Lew

Arne Vajhøj - 20 Apr 2008 02:23 GMT
> BoBi wrote:
>>   ResultSet rs = pstmt.getGeneratedKeys();
>
> If only you were using PostgreSQL, you could use their extension to the
> INSERT command:
>   [ RETURNING * | output_expression [ AS output_name ] [, ...] ]

But since we of course try to write database independent code, then
we will not use that even if our current database happen to
be PostgreSQL ...

The getGeneratedKeys method is database independent - it just require
a JDBC 3.0 compliant driver.

Arne
BoBi - 02 May 2008 09:59 GMT
> > BoBi wrote:
> >>   ResultSet rs = pstmt.getGeneratedKeys();
[quoted text clipped - 11 lines]
>
> Arne

I totally agree. :c), BoBi
Jim Garrison - 03 May 2008 04:18 GMT
>>> BoBi wrote:
>>>>   ResultSet rs = pstmt.getGeneratedKeys();
[quoted text clipped - 7 lines]
>> The getGeneratedKeys method is database independent - it just require
>> a JDBC 3.0 compliant driver.

Try comparing the Oracle and MSSQL implementations of this supposedly
"database independent" feature.  Oracle gets it right and supports
the API: you provide an array of column names in the PrepareStatement(),
and Oracle returns their values for the newly inserted row.  MSSQL
throws a SQLException if the array contains more than one element, and
always returns the single "identity" column value regardless of the
column name you specified.
Arne Vajhøj - 15 May 2008 02:19 GMT
>>>> BoBi wrote:
>>>>>   ResultSet rs = pstmt.getGeneratedKeys();
[quoted text clipped - 15 lines]
> always returns the single "identity" column value regardless of the
> column name you specified.

It has to because that is what SQLServer does.

Portable database code will assume only one auto generated
column, because half the databases only support that.

From what you say there is a bug where it does not throw an
exception the if the specified column index is not the actual
identity column.

That bug should obviously be fixed.

But the JDBC driver can not by magic make non standard
features work on a database that does not support it.

Arne
BoBi - 21 Mar 2008 08:40 GMT
> > Hello,
>
[quoted text clipped - 72 lines]
> David Harper
> Cambridge, England

Thanks alot for the solution and advice. :c), BoBi


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.