Home Tutorial Java Core JDBC: Alter Table Example

 
 

JDBC: Alter Table Example
Posted on: September 27, 2012 at 12:00 AM
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
			Class.forName(driverName);
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {
				Statement st = con.createStatement();
				String sql = "ALTER TABLE student add location varchar(30)";
				st.executeUpdate(sql);
				System.out.println("Table is altered successfully");
			} catch (SQLException s) {
				System.out.println(s);
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output :

Table Alter Example!
Table is altered successfully

Now Your table looks like this -

Related Tags for JDBC: Alter Table Example:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.