Table Creation in SQL Using Java


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class CreateTableWithStatement
{
  public static void main(String[] args)
  {
    String tableCreateQuery = "create table xyz77(name varchar2(10), course varchar2(10))";
    Statement statement = null;
    Connection connection = null;
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please provide below details to connect Oracle Database");
    System.out.println("Enter Database");
    String dbName = scanner.next();
    System.out.println("Enter UserName");
    String userName = scanner.next();
    System.out.println("Enter Password");
    String password = scanner.next();
    try
    {
      Class.forName("oracle.jdbc.driver.OracleDriver");
    }
    catch (ClassNotFoundException e)
    {
      e.printStackTrace();
    }
    try
    {
      connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:" + dbName, userName,password);
    }
    catch (SQLException e)
    {
      e.printStackTrace();
    }
    if (connection != null)
    {
      System.out.println("Successfully connected to Oracle DB");
      try
      {
        statement = connection.createStatement();
        System.out.println("Create Table Query :"+tableCreateQuery);
        statement.execute(tableCreateQuery);
        System.out.println("Table Created Successfully");
      }
      catch (SQLException e)
      {
        e.printStackTrace();
      }
    }
    else
    {
      System.out.println("Failed to connect to Oracle DB");
    }
  }
}

0 Comments