Welcome to dbFreaks.com!
FAQFAQ    SearchSearch      ProfileProfile    Private MessagesPrivate Messages   Log inLog in

Getting a Mysql auto increment value back into my Java cli..

 
   Database Help (Home) -> Java RSS
Next:  A free tool like Erwin  
Author Message
BoBi

External


Since: Mar 19, 2008
Posts: 3



(Msg. 1) Posted: Wed Mar 19, 2008 11:33 am
Post subject: Getting a Mysql auto increment value back into my Java client GUI?
Archived from groups: comp>lang>java>databases (more info?)

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

 >> Stay informed about: Getting a Mysql auto increment value back into my Java cli.. 
Back to top
Login to vote
David Harper

External


Since: Jan 25, 2004
Posts: 32



(Msg. 2) Posted: Wed Mar 19, 2008 9:20 pm
Post subject: Re: Getting a Mysql auto increment value back into my Java client [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

BoBi wrote:
> 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?

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

 >> Stay informed about: Getting a Mysql auto increment value back into my Java cli.. 
Back to top
Login to vote
Lew

External


Since: Feb 15, 2008
Posts: 43



(Msg. 3) Posted: Wed Mar 19, 2008 9:20 pm
Post subject: Re: Getting a Mysql auto increment value back into my Java client [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

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?

David Harper wrote:
> 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();

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>

--
Lew
 >> Stay informed about: Getting a Mysql auto increment value back into my Java cli.. 
Back to top
Login to vote
BoBi

External


Since: Mar 19, 2008
Posts: 3



(Msg. 4) Posted: Fri Mar 21, 2008 12:40 am
Post subject: Re: Getting a Mysql auto increment value back into my Java client [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

On Mar 19, 10:20 pm, David Harper wrote:
> BoBi wrote:
> > 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
> > (seehttp://www.dongo.orgto 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?
>
> 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

Thanks alot for the solution and advice. :c), BoBi
 >> Stay informed about: Getting a Mysql auto increment value back into my Java cli.. 
Back to top
Login to vote
Arne Vajhøj

External


Since: Mar 10, 2008
Posts: 3



(Msg. 5) Posted: Sat Apr 19, 2008 9:23 pm
Post subject: Re: Getting a Mysql auto increment value back into my Java client [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

Lew wrote:
> 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
 >> Stay informed about: Getting a Mysql auto increment value back into my Java cli.. 
Back to top
Login to vote
BoBi

External


Since: Mar 19, 2008
Posts: 3



(Msg. 6) Posted: Fri May 02, 2008 1:59 am
Post subject: Re: Getting a Mysql auto increment value back into my Java client [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

On Apr 20, 3:23 am, Arne Vajhøj wrote:
> Lew wrote:
> > 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

I totally agree. :c), BoBi
 >> Stay informed about: Getting a Mysql auto increment value back into my Java cli.. 
Back to top
Login to vote
Jim Garrison

External


Since: May 02, 2008
Posts: 1



(Msg. 7) Posted: Fri May 02, 2008 10:18 pm
Post subject: Re: Getting a Mysql auto increment value back into my Java client [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

BoBi wrote:
> On Apr 20, 3:23 am, Arne Vajhøj wrote:
>> Lew wrote:
>>> 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.

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.
 >> Stay informed about: Getting a Mysql auto increment value back into my Java cli.. 
Back to top
Login to vote
Arne_Vajhøj

External


Since: Mar 02, 2008
Posts: 37



(Msg. 8) Posted: Wed May 14, 2008 9:19 pm
Post subject: Re: Getting a Mysql auto increment value back into my Java client [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

Jim Garrison wrote:
> BoBi wrote:
>> On Apr 20, 3:23 am, Arne Vajhøj wrote:
>>> Lew wrote:
>>>> 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.
>
> 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.

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
 >> Stay informed about: Getting a Mysql auto increment value back into my Java cli.. 
Back to top
Login to vote
Display posts from previous:   
Related Topics:
Java &amp; MySQL show table status command - Hi, I am using java to retrieve a resultset with "show table status" mysql command. I am having problem reading the [name] and [engine] column. In the metadata object it is showing as VARCHAR but when I do getString() it is returning me the o...

Java Requierment - Hi, Dear business partners we have an urgent requirement on .net developer Thanks & Regards Pavani.c2c@gmail.com Pavani_savvy@gmail.com

Need to Learn about the Java ODBC - From February to July of last year I worked for a company where I wrote C code that accessed a PostgreSQL database with SQL commands and generated the output my supervisor wanted. Now I'm working for a different company that doesn't have a C..

free database for java - Hello. I am looking for best free database for java & navigator tool (Till I found someone to invest on my software ...) After I have asked some people : I have found Derby db & Squirrel-sql db-navigator. .... but I see some opinions that Derb...

Java Database for mobile phone - I'm searching for a simple Java database for mobile phone (motorola v550). I would like to create a database with few fields containing texts. Is there some free/shareware software? Is there a very simple Java spreadsheet for mobile phone motorola v550?...
   Database Help (Home) -> Java All times are: Pacific Time (US & Canada)
Page 1 of 1

 
You can post new topics in this forum
You can reply to topics in this forum
You can edit your posts in this forum
You can delete your posts in this forum
You can vote in polls in this forum



[ Contact us | Terms of Service/Privacy Policy ]