Getting the MySQL database to generate my primary keys
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Paul_Hunnisett
Posted On:   Friday, October 17, 2003 09:12 AM

I need to insert my data into a MySQL database table using an INSERT statement which I will build up using a PreparedStatement in Java.

Ideally, however, I don't want to have to programatically create a unique primary key. Is there a way of getting MySQL to do this for me? If so, how should my insert statement look to take advantage of this functionality?

Any help would be much appreciated.

Re: Getting the MySQL database to generate my primary keys

Posted By:   Christopher_Schultz  
Posted On:   Friday, October 17, 2003 11:50 AM

First, You need to create your PK column in MySQL with the auto_increment keyword.



Then, you need to omit the PK column from the INSERT statement, like this:



INSERT INTO my_table (non-pk-col1, non-pk-col2, ...) VALUES (...)



MySQL will automatically generate the PK for you. If you're using JDBC 3.0 (I think... maybe it's 2.0), you can use the PreparedStatement.getGeneratedKeys method to determine the new PK created.



Hope that helps,

-chris
About | Sitemap | Contact