Share on Google+Share on Google+

JDBC: Alter Table Example

This tutorial describe how to alter existing table using JDBC API.

JDBC: Alter Table Example

This tutorial describe how to alter existing table using JDBC API.

Alter Table :

Alter table means editing the existing table. You can add new field, drop unused field and alter properties of field.
We can change the structure of table student in the following ways -

  1. You can add new field -
     sql= " ALTER TABLE student ADD location varchar(30)"
  2. You can delete the unused field-
    sql="ALTER TABLE student DROP location"
  3. You can replace the existing field name with new name.
    sql="ALTER TABLE student CHANGE  location address varchar(30)"
  4. You can also alter the field definition.
    sql="ALTER TABLE student ALTER  location SET DEFAULT 'New Delhi' "
  5. You can alter the field definition by using MODIFY keyword.
    sql="ALTER TABLE student MODIFY  roll_no varchar(20) "

Example : In this example we are adding new field 'location' to the table 'student'.

package jdbc;

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

class AlterTable {
	public static void main(String[] args) {
		System.out.println("Table Alter 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 {
			// Creating db connection
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {
				Statement st = con.createStatement();
				String sql = "ALTER TABLE student add location varchar(30)";
				System.out.println("Table is altered successfully");
			} catch (SQLException s) {
		} catch (Exception e) {

Output :

Table Alter Example!
Table is altered successfully

Now Your table looks like this -



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.