Create database table using Java program

Q. Write a program to create a database table by using Java program.

Answer:

Below example shows how to create a table is SQL database by using Java program. The table name is Student with column stdId and studName.

We use the oracle 11g database with type 4 driver. There is no need of any third party vendor for type 4 driver.

CreateDBTable.java

import java.sql.*;
public class CreateDBTable
{
     Connection con;
     CreateDBTable()
     {
          try
          {
               Class.forName("oracle.jdbc.driver.OracleDriver");
               //create connection object
               con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","local","test");
               //create PreparedStatement object
               PreparedStatement ps=con.prepareStatement("create table Student(stdId int primary key,studName VARCHAR(30) not null )");
               //execute the sql query
               int count=ps.executeUpdate();//returns 0
               System.out.println(count);
               System.out.println("Table created successfully!!");
          }
          catch (Exception e)
          {
               e.printStackTrace();
          }
     }
     public static void main(String s[])
     {
          new CreateDBTable();
     }
}


Output:  

Table created successfully!!