Open In App

Java JDBC – Update a Column in a Table

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 java application to our database using JDBC.

Note: Load mysqlconnector.jar into your program.



Steps:




// Update a Column in a Table
  
// 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
            Class.forName("com.mysql.jdbc.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 RollNo is the new column
            String query
                = "ALTER TABLE student RENAME COLUMN roll_no TO RollNo";
  
            // 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(
                    "table successfully updated.");
            else
                System.out.println("unable to update");
  
            // closing connection
            conn.close();
        }
        catch (SQLException e) {
            System.out.println(e);
        }
    }
}




Article Tags :