Open In App

How to Add a New Column to a Table Using JDBC API?

Last Updated : 08 Dec, 2020
Like Article

Java has its own API which JDBC API which uses JDBC drivers for database connections. JDBC API provides the applications-to-JDBC connection and JDBC driver provides a manager-to-driver connection.

Following are the 5 important steps to connect the java application to our database using JDBC.

  1. Registering the Java class
  2. Creating a connection
  3. Creating a statement
  4. Executing queries
  5. Closing connection

Note: Load mysqlconnector.jar into your program.


  • Download MySQLConnect/J (JDBC connector jar file) from the following link
  • Select platform-independent in select OS option
  • Copy mysql-connector-java-5.1.34-bin.jar file in your project
  • Right-click on it, select Build Path ⇾ Configure Build path ⇾ libraries ⇾ Add JARS
  • In JAR selection window, select mysql-connector-java-5.1.34-bin.jar library under your project
  • Click OK

 Create a Database, add a table with records using MySQL cmd. 


// Java program to add a column to a table using JDBC
// dont forget to import below package
import java.sql.*;
public class Database {
    // url that points to mysql database,
    // 'db' is database name
    static final String url
        = "jdbc:mysql://localhost:3306/db";
    public static void main(String[] args)
        throws ClassNotFoundException
        try {
            // this Class.forName() method is user for
            // driver registration with name of the driver
            // as argument i have used MySQL driver
            // getConnection() establishes a connection. It
            // takes url that points to your database,
            // username and password of MySQL connections as
            // arguments
            Connection conn = DriverManager.getConnection(
                url, "root", "1234");
            // create.Statement() creates statement object
            // which is responsible for executing queries on
            // table
            Statement stmt = conn.createStatement();
            // Executing the query, student is the table
            // name and age is the new column
            String query
                = "ALTER TABLE student ADD COLUMN age INT";
            // executeUpdate() is used for INSERT, UPDATE,
            // DELETE statements.It returns number of rows
            // affected by the execution of the statement
            int result = stmt.executeUpdate(query);
            // if result is greater than 0, it means values
            // has been added
            if (result > 0)
                System.out.println("new column added.");
                    "unable to add a column.");
            // closing connection
        catch (SQLException e) {

Add a new columnOutput of the table content after adding new column

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads