get id after insert

Post here your questions about SFS2X. Here we discuss all server-side matters. For client API questions see the dedicated forums.

Moderators: Lapo, Bax

sebako
Posts: 20
Joined: 22 Jan 2011, 02:06
Location: Ireland
Contact:

get id after insert

Postby sebako » 20 May 2011, 17:05

Hey guys,

I am inserting something into a database table which works fine:

Code: Select all

stmt = con.prepareStatement("INSERT INTO `planet` (`user_id`, `main`, `size`, `type`, `seed`) VALUES (?, ?, ?, ?, ?);");
                stmt.setInt(1, dbId);
                stmt.setInt(2, 1);
                stmt.setInt(3, pl.size);
                stmt.setInt(4, pl.type);
                stmt.setFloat(5, pl.seed);
                stmt.execute();


now my question is how I would get the Id (primary key) of the inserted field without querying it again directly? Is that possible?

Thanks

Seb
User avatar
rjgtav
Posts: 2813
Joined: 19 Apr 2009, 11:31
Location: Lisbon, Portugal

Postby rjgtav » 20 May 2011, 22:15

hi. Unfortunately i think the only way is querying it. Maybe some1 knows another way?
Skills: SFS Pro, SFS2X, AS2.0/AS3.0, Java, HTML5/CSS3/JS, C#
Portfolio: https://rjgtav.wordpress.com/
SFS Tutorials: http://sfs-tutor.blogspot.com/ - Discontinued. Some examples may be bugged.
kincade
Posts: 7
Joined: 04 Feb 2011, 13:27
Location: Croatia

Postby kincade » 23 May 2011, 08:00

If your DB is MySQL then you can try the following:

Code: Select all

connection = connectionPool_.getConnection();
String query = "INSERT INTO event (title, type) VALUES (?, ?)";      
PreparedStatement statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
statement.setString(1, event.getTitle());
statement.setInt(2, event.getType());
statement.executeUpdate();        
// get event id
ResultSet keys = statement.getGeneratedKeys();   
keys.next();
int eventId = keys.getInt(1);

For other DB vendors there should be something similar - just google it.
sebako
Posts: 20
Joined: 22 Jan 2011, 02:06
Location: Ireland
Contact:

Postby sebako » 23 May 2011, 10:28

alright this works - thanks kincade :)

Return to “SFS2X Questions”

Who is online

Users browsing this forum: No registered users and 102 guests