Lauthai
Lauthai

Reputation: 305

How to auto-increment a column in a MySQL table?

Ok so I am making a program in Java where it sends data to a MySQL server where it makes a new account. The table has 4 columns. ID, e-mail, username, and password. I know how to set the values of e-mail, username, and password but I need help setting ID. ID will auto-increment based on the last registered ID in the table.

Example: If the last registered user had an ID of 4 then it will auto-set the new user's ID to 5.

Upvotes: 0

Views: 1205

Answers (4)

unixmiah
unixmiah

Reputation: 3145

Like this:

ALTER TABLE Persons AUTO_INCREMENT=100 //use this if you want a certain number to start off from

To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically):

INSERT INTO table (email, username, password)
VALUES ('email@domain','unixmiah', 'x007')

Upvotes: 0

unixmiah
unixmiah

Reputation: 3145

this is the way, you need to set your ID field to auto increment. If you have phpmyadmin you can do it easily on the UI otherwise you can do it on mysql command line.

ALTER TABLE table ADD ID int NOT NULL AUTO_INCREMENT

Upvotes: 1

brso05
brso05

Reputation: 13222

Make sure the column ID is set to auto increment in your database then when you do your insert specify all the fields except the ID field and it will automatically be populated with the next ID.

Upvotes: 0

Pupil
Pupil

Reputation: 23948

Edit the I'd field IN MYSQL client and set it to AUTO INCREMENT

Upvotes: 0

Related Questions