Sunday, 22 March 2020

Jdbc: Drop table

Below snippet is used to drop ‘employee’ table.
Connection conn = DriverManager.getConnection(url, userName, pasword);
Statement stmt = conn.createStatement();
String sql = "DROP TABLE employee";
stmt.executeUpdate(sql);

App.java
package com.sample.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class App {

 // Initialize url username and password
 private static final String URL = "jdbc:mysql://localhost/sample";
 private static final String USERNAME = "krishna";
 private static final String PASSWORD = "krishna";

 public static void main(String args[]) throws SQLException, ClassNotFoundException {

  /* Open connection to database */
  System.out.println("Connecting to database");

  Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);

  /* Create table employee */
  String query = "CREATE TABLE employee (id int, firstName varchar(30), lastName varchar(30), PRIMARY KEY(id))";
  Statement stmt = conn.createStatement();
  stmt.execute(query);

  /* Insert data to employee table */
  query = "INSERT INTO employee values(1, \"Krishna\",  \"Gurram\")";
  stmt.execute(query);
  query = "INSERT INTO employee values(2, \"Gopi\",  \"Battu\")";
  stmt.execute(query);

  query = "SELECT * FROM employee";
  ResultSet rs = stmt.executeQuery(query);

  while (rs.next()) {
   int id = rs.getInt("id");
   String firstName = rs.getString("firstName");
   String lastName = rs.getString("lastName");
   System.out.println(id + " " + firstName + " " + lastName);
  }

  System.out.println("Dropping the table employee");

  String sql = "DROP TABLE employee";

  stmt.executeUpdate(sql);

  rs.close();
  conn.close();
  conn.close();
 }
}

Output
Connecting to database
1 Krishna Gurram
2 Gopi Battu
Dropping the table employee


Previous                                                    Next                                                    Home

No comments:

Post a Comment