JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

"CREATE TABLE" Statements

This section describes how to create a table in the current database.

"CREATE TABLE" is probably the most commonly used DDL statement. Its syntax is relatively simple. All you need to do is to specify the table name with an optional schema name and a list of column definitions.

The sample Java program below shows you how to create a table called "Price" in "Herong" schema. I defined only three columns in this table: ProductID, Price, and Currency.

/**
 * CreateTable.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.sql.*;
public class CreateTable {
  public static void main(String [] args) {
    Connection con = null;
    try {

      Class.forName(
        "com.microsoft.sqlserver.jdbc.SQLServerDriver");

      con = DriverManager.getConnection(
          "jdbc:sqlserver://localhost:1269;"
        + "user=sa;password=HerongYang;"
        + "database=AdventureWorksLT");

// Altering a database table with an extra column
      Statement sta = con.createStatement(); 
      int count = sta.executeUpdate(
        "CREATE TABLE Herong.Price (ProductID INT, Price REAL,"
        + " Currency CHAR(3))");
      System.out.println("Table created.");
      sta.close();        

      con.close();        
    } catch (java.lang.ClassNotFoundException e) {
      System.err.println("ClassNotFoundException: "
        +e.getMessage());
    } catch (SQLException e) {
      System.err.println("SQLException: "
        +e.getMessage());
    }
  }
}

If you run this program a new table will be created with the following message.

Table created.

Sections in This Chapter

Executing "Update" Statements - executeUpdate()

"CREATE SCHEMA" Statements

"CREATE TABLE" Statements

"ALTER TABLE" Statements

"DROP TABLE" Statements

Dr. Herong Yang, updated in 2007
"CREATE TABLE" Statements