How to create a table in Oracle using JDBC?

You can create a table in a database using the CREATE TABLE query.


CREATE TABLE table_name(
   column1 datatype,
   column2 datatype,
   column3 datatype,
   columnN datatype,
   PRIMARY KEY( one or more columns )

To create a table in a database using JDBC API you need to −

Register the Driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter.

Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.

Create Statement: Create a Statement object using the createStatement() method of the Connection interface.

Execute the Query: Execute the query using the execute() method of the Statement interface.

Following JDBC program establishes connection with Oracle database and creates a table named DISPATCHES −


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTable_Oracle {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      //Getting the connection
      String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
      Connection con = DriverManager.getConnection(oracleUrl, "system", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to create a table
      String query = "CREATE TABLE DISPATCHES("
      + "ProductName VARCHAR (20) NOT NULL, "
      + "CustomerName VARCHAR (20) NOT NULL, "
      + "DispatchDate date, "
      + "DeliveryTime timestamp, "
      + "Price INT, "
      + "Location varchar(20))";
      System.out.println("Table Created......");


Connection established......
Table Created......

In oracle you can get the list of tables using the query/command −

Select * from tab;

If you verify the list of tables in the database using this, you can observe the newly created table in it as −

Vikyath Ram
Vikyath Ram

A born rival