Home Tutorial Java Core JDBC: Alter Table Example


Share on Google+Share on Google+
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
			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 -


Related Tags for JDBC: Alter Table Example:

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.

Posted on: September 27, 2012

Recommend the tutorial

Advertisements Advertisements