3

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

3
  • Do you use Spring JdbcTemplate? Commented Jul 11, 2012 at 8:50
  • @QuickSilver - no. Did you not read what the bolded part says? Commented Jul 11, 2012 at 8:57
  • not using Spring JdbcTemplate only JDBC Commented Jul 11, 2012 at 8:59

3 Answers 3

5
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
Sign up to request clarification or add additional context in comments.

1 Comment

i try like this it give error mysql> insert into userstable(column1, column2) values ((select max(column1) from table)+1, 79); ERROR 1093 (HY000): You can't specify target table 'userstable' for update in FROM clause
0

Lets try this once (not tested)

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

For ex,

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

1 Comment

its working fine i have one more doubt suppose we have 9 columns when one column is deleted then again it stores 9 for the column1 or not?
-1

if you want the auto value of column1, don't set it, just let it get a defult value

INSERT INTO table (column2) values(?)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.