JDBC Tutorial - JDBC Create Table








The following code shows how to create a new table through JDBC connection.

It issues the following SQL command to create a table.

CREATE TABLE Person
(id INTEGER not NULL, 
 firstName VARCHAR(50), 
 lastName VARCHAR(50), 
 age INTEGER, 
 PRIMARY KEY ( id ))




Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
//www .j a  v  a2s . co  m
public class Main {
  static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

  static final String USER = "username";
  static final String PASS = "password";

  public static void main(String[] args) throws Exception {
    Connection conn = null;
    Statement stmt = null;

    Class.forName(JDBC_DRIVER);
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    System.out.println("Deleting database...");
    stmt = conn.createStatement();

    conn = DriverManager.getConnection(DB_URL, USER, PASS);

    stmt = conn.createStatement();

    String sql = "CREATE TABLE Person" 
            + "(id INTEGER not NULL, "
        + " firstName VARCHAR(50), " 
            + " lastName VARCHAR(50), "
        + " age INTEGER, " 
            + " PRIMARY KEY ( id ))";

    stmt.executeUpdate(sql);
    System.out.println("Created table in given database...");
    stmt.close();
    conn.close();
  }
}




PreparedStatement to create a table

The following code shows how to use PreparedStatement to create a table.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/*w  w w .  ja  v  a2 s.  c  om*/
public class Main {
  private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
  private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:YourDatabase";
  private static final String DB_USER = "user";
  private static final String DB_PASSWORD = "password";

  public static void main(String[] argv) throws Exception {
    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;

    String createTableSQL = "CREATE TABLE Person("
        + "USER_ID NUMBER(5) NOT NULL, "
        + "USERNAME VARCHAR(20) NOT NULL, "
        + "CREATED_BY VARCHAR(20) NOT NULL, "
        + "CREATED_DATE DATE NOT NULL, " 
        + "PRIMARY KEY (USER_ID) "
        + ")";

    Class.forName(DB_DRIVER);
    dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,
        DB_PASSWORD);

    preparedStatement = dbConnection.prepareStatement(createTableSQL);

    System.out.println(createTableSQL);

    preparedStatement.executeUpdate();

    preparedStatement.close();
    dbConnection.close();

  }
}