Share on Google+Share on Google+

JDBC: MYSQL Auto_Increment key Example

In this tutorial we are setting one field of table auto_incremented using JDBC API.

JDBC: MYSQL Auto_Increment key Example

In this tutorial we are setting one field of table auto_incremented using JDBC API.

Auto_Increment key : Auto_Increment key is used for automatically increment the value of the field. Since its is done automatically so no need to specify value of that field. At the time of table creation just specify AUTO_INCREMENT key for your willing field.

Example : In this example, we are creating table "department" and declaring field 'id' as AUTO_INCREMENT.

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

class AutoIncrementValue{
	public static void main(String[] args) {
		System.out.println("MySql Auto increment  Example!");
		Connection con = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "students";
		String driverName = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		try {
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {
				System.out.println("Using AUTO_INCREMENT key for 'id' field");
				Statement st = con.createStatement();
				String sql = "CREATE TABLE department(id int NOT NULL AUTO_INCREMENT,name varchar(30),PRIMARY KEY(id))";
				System.out.println("Table is created successfully");
			} catch (SQLException s) {
		} catch (Exception e) {

Output :

MySql Auto increment  Example!
Using AUTO_INCREMENT key for 'id' field
Table is created successfully

You can also see your table in database. It will display details of your table 'department' -

Field   Type         Collation          Null    Key     Default  Extra           Privileges                       Comment
------  -----------  -----------------  ------  ------  -------  --------------  -------------------------------  -------
id      int(11)      (NULL)             NO      PRI     (NULL)   auto_increment  select,insert,update,references         
name    varchar(30)  latin1_swedish_ci  YES             (NULL)                   select,insert,update,references         


Posted on: September 27, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.