Share on Google+Share on Google+

Deleting row and column from a table

Advertisement
In this program ,we delete row and column of a table.

Deleting row and column from a table 

In this program ,we delete row and column of a table. First we create connection to a database using connection interface and java driver. After it we can delete row using "delete " keyword and also can delete column using "Alter" table commands SQL.

For this example, we are using a database named as "cellular" of mysql--

cellular(Before deletion)--

In this table we will delete,id having minimum value and we will also delete column "name".

import java.sql.*; 


class colerase {
      public static void main(String[] args) throws SQLException {

            // declare a connection by using Connection interface 
            Connection connection = null;

           

            String connectionURL = "jdbc:mysql://192.168.10.13:3306/ankdb";

            //declare a resultSet 
            ResultSet rs = null;

            // Declare statement.
            Statement statement = null;

            try {

                // Load JDBC driver "com.mysql.jdbc.Driver". 
                Class.forName("com.mysql.jdbc.Driver").newInstance();

                
                connection = DriverManager.getConnection(connectionURL,
                "root", "root");

                
                statement = connection.createStatement();

               

    /* sql query find the element from the table havinf minimum ID */
    rs = statement.executeQuery("select min(id) from cellular");
    rs.next();
        

    // This sql query delete the row having minimum ID.
 statement.executeUpdate("delete from cellular where id='"+rs.getInt(1)+"'");  
 System.out.println("Row is deleted successfully.");

         

                // This sql query delete the column name of specified name.
 statement.executeUpdate("ALTER TABLE cellular DROP name");
 System.out.println("column 'Address' is deleted successfully.");

               
     }
     // catch exceptions if found any exception at run time.
     catch(Exception ex){
              System.out.println("Sorry ! found some problems with database.");
        System.out.println("Error is : "+ ex);
          }

           finally {
                // close all the connections.
                rs.close();
                statement.close();
                connection.close();
          }
      }
}

cellular(after deletion of minimum "id" value and column "name")

Advertisements

Advertisement

Posted on: May 31, 2010 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.