JDBC: MYSQL Auto_Increment key Example


 

JDBC: MYSQL Auto_Increment key Example

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

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 {
			Class.forName(driverName);
			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))";
				st.executeUpdate(sql);
				System.out.println("Table is created successfully");
			} catch (SQLException s) {
				System.out.println(s);
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

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         

Ads