JDBC 创建表

2018-03-21 14:11 更新

JDBC教程 - JDBC创建表


以下代码显示如何通过JDBC连接创建新表。

它发出以下SQL命令来创建表。

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

例子

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

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创建一个表

以下代码显示如何使用Prepared Statement创建表。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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();

  }
}
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号