Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Auto increment a column in mysql table through java

Tags:

java

mysql

i have table with 2 columns 1.column1 2.column2(its unique) now through java coding i am inserting data through 2 methods in the first method i want to insert data ,in this coumn1 filed should be auto increment(for new user)

String sql = "INSERT INTO table (column1, column2) values(?, ?)";
pstm = connection.prepareStatement(sql);

    pstm.setInt(1, auto_incrmentvalue need to set);
    pstm.setInt(2,column2);

in the second method insert data with what i want

String sql = "INSERT INTO table (column1, column2) values(?, ?)";
pstm = connection.prepareStatement(sql);

    pstm.setInt(1, column1);
    pstm.setInt(2,column2);

how to set auto increment value in the first method

NOTE:Here column1 is not a primary key

like image 360
Rajeswari Kotikalapudi Avatar asked Jan 27 '26 14:01

Rajeswari Kotikalapudi


1 Answers

INSERT INTO table(column1) SELECT MAX(column1)+1 FROM table

This one worked for me

Please see INSERT...SELECT

Your query should be like this,

INSERT INTO table(column1, column2) SELECT MAX(column1)+1, 79  FROM table

More refined answer:

INSERT INTO
     usertable(column1, column2) 
     SELECT CASE COUNT(column1) 
         WHEN 0 THEN 0 
         ELSE MAX(column1) END+1,
     79 FROM usertable

This could be a more simple solution:

INSERT INTO usertable(column1, column2) 
SELECT IFNULL(MAX(column1)+1,1),79 FROM usertable
like image 176
Quicksilver Avatar answered Jan 29 '26 03:01

Quicksilver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!