JDBCステートメントの例 - テーブルを作成する

次に、JDBCステートメントを使用してデータベースにテーブルを作成する方法を示す例を示します。 create文を発行するには、次のようにS`tatement.execute() `メソッドを呼び出します。

Statement statement = dbConnection.createStatement();//execute create SQL stetement
statement.execute(createTableSQL);

完全な例…​

package com.mkyong.jdbc;

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

public class JDBCStatementCreateExample {

    private static final String DB__DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DB__CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
    private static final String DB__USER = "user";
    private static final String DB__PASSWORD = "password";

    public static void main(String[]argv) {

        try {

            createDbUserTable();

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        }

    }

    private static void createDbUserTable() throws SQLException {

        Connection dbConnection = null;
        Statement statement = null;

        String createTableSQL = "CREATE TABLE DBUSER("
                + "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) "
                + ")";

        try {
            dbConnection = getDBConnection();
            statement = dbConnection.createStatement();

            System.out.println(createTableSQL);
                       //execute the SQL stetement
            statement.execute(createTableSQL);

            System.out.println("Table \"dbuser\" is created!");

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        } finally {

            if (statement != null) {
                statement.close();
            }

            if (dbConnection != null) {
                dbConnection.close();
            }

        }

    }

    private static Connection getDBConnection() {

        Connection dbConnection = null;

        try {

            Class.forName(DB__DRIVER);

        } catch (ClassNotFoundException e) {

            System.out.println(e.getMessage());

        }

        try {

            dbConnection = DriverManager.getConnection(
                    DB__CONNECTION, DB__USER,DB__PASSWORD);
            return dbConnection;

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        }

        return dbConnection;

    }

}

結果

ここに結果があります。

CREATE TABLE DBUSER(
  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)
)
Table "user" is created!

create jdbc ステートメント リンク://タグ/テーブル/[テーブル]