How to add an auto increment column in java?

Ankush Tyagi picture Ankush Tyagi · Jul 9, 2015 · Viewed 15.3k times · Source

I want to add the database from my jform and there's a column which will be auto incremented, like when i click done, the data will be inserted and a column receipt_no will have a value 1. Next time I click done then this value should be 2 and so on.

So the problem is, i have created a table with receipt_no as the primary key and auto increment, so what should be my query in java, to add the data correctly in the table.

String sql = "insert into table_name values('"++"',...)";

Can you help me in this query?

Answer

Vicky Thakor picture Vicky Thakor · Jul 9, 2015

Step 1: Creating table in MySQL

CREATE TABLE `user_master` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Firstname` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 2: Insert record

INSERT INTO user_master (`Firstname`) values('Vicky');

Step 3: Fetch record

SELECT * FROM user_master;