Documentation

The Java™ Tutorials
Hide TOC
Setting Up Tables设置表
Trail: JDBC Database Access
Lesson: JDBC Basics

Setting Up Tables

This page describes all the tables used in the JDBC tutorial and how to create them:本页介绍JDBC教程中使用的所有表以及如何创建它们:

COFFEES Table

The COFFEES table stores information about the coffees available for sale at The Coffee Break:COFFEES表存储咖啡休息时可供出售的咖啡的相关信息:

COF_NAME SUP_ID PRICE SALES TOTAL
Colombian 101 7.99 0 0
French_Roast 49 8.99 0 0
Espresso 150 9.99 0 0
Colombian_Decaf 101 8.99 0 0
French_Roast_Decaf 49 9.99 0 0

The following describes each of the columns in the COFFEES table:以下描述了COFFEES表中的每一列:

SUPPLIERS Table

The SUPPLIERS stores information about each of the suppliers:SUPPLIERS表存储关于每个供应商的信息:

SUP_ID SUP_NAME STREET CITY STATE ZIP
101 Acme, Inc. 99 Market Street Groundsville CA 95199
49 Superior Coffee 1 Party Place Mendocino CA 95460
150 The High Ground 100 Coffee Lane Meadows CA 93966

The following describes each of the columns in the SUPPLIERS table:以下描述了SUPPLIERS表中的每一列:

COF_INVENTORY Table

The table COF_INVENTORY stores information about the amount of coffee stored in each warehouse:COF_INVENTORY表存储关于每个仓库中存储的咖啡量的信息:

WAREHOUSE_ID COF_NAME SUP_ID QUAN DATE_VAL
1234 House_Blend 49 0 2006_04_01
1234 House_Blend_Decaf 49 0 2006_04_01
1234 Colombian 101 0 2006_04_01
1234 French_Roast 49 0 2006_04_01
1234 Espresso 150 0 2006_04_01
1234 Colombian_Decaf 101 0 2006_04_01

The following describes each of the columns in the COF_INVENTORY table:以下描述了COF_INVENTORY表中的每一列:

MERCH_INVENTORY TableMERCH_库存表

The table MERCH_INVENTORY stores information about the amount of non-coffee merchandise in stock:MERCH_INVENTORY表存储关于库存中非咖啡商品数量的信息:

ITEM_ID ITEM_NAME SUP_ID QUAN DATE
00001234 Cup_Large 00456 28 2006_04_01
00001235 Cup_Small 00456 36 2006_04_01
00001236 Saucer 00456 64 2006_04_01
00001287 Carafe 00456 12 2006_04_01
00006931 Carafe 00927 3 2006_04_01
00006935 PotHolder 00927 88 2006_04_01
00006977 Napkin 00927 108 2006_04_01
00006979 Towel 00927 24 2006_04_01
00004488 CofMaker 08732 5 2006_04_01
00004490 CofGrinder 08732 9 2006_04_01
00004495 EspMaker 08732 4 2006_04_01
00006914 Cookbook 00927 12 2006_04_01

The following describes each of the columns in the MERCH_INVENTORY table:以下描述了MERCH_INVENTORY表中的每一列:

COFFEE_HOUSES Table

The table COFFEE_HOUSES stores locations of coffee houses:COFFEE_HOUSES表存储咖啡馆的位置:

STORE_ID CITY COFFEE MERCH TOTAL
10023 Mendocino 3450 2005 5455
33002 Seattle 4699 3109 7808
10040 SF 5386 2841 8227
32001 Portland 3147 3579 6726
10042 SF 2863 1874 4710
10024 Sacramento 1987 2341 4328
10039 Carmel 2691 1121 3812
10041 LA 1533 1007 2540
33005 Olympia 2733 1550 4283
33010 Seattle 3210 2177 5387
10035 SF 1922 1056 2978
10037 LA 2143 1876 4019
10034 San_Jose 1234 1032 2266
32004 Eugene 1356 1112 2468

The following describes each of the columns in the COFFEE_HOUSES table:以下描述了COFFEE_HOUSES表中的每一列:

DATA_REPOSITORY Table数据存储库表

The table DATA_REPOSITORY stores URLs that reference documents and other data of interest to The Coffee Break. table DATA_存储库存储引用文档和咖啡休息时间感兴趣的其他数据的URL。The script populate_tables.sql does not add any data to this table. 脚本populates_tables.sql不会向该表添加任何数据。The following describes each of the columns in this table:下表介绍了该表中的每一列:

Creating Tables创建表

You can create tables with Apache Ant or JDBC API.您可以使用ApacheAnt或JDBCAPI创建表。

Creating Tables with Apache Ant使用ApacheAnt创建表

To create the tables used with the tutorial sample code, run the following command in the directory <JDBC tutorial directory>:要创建与教程示例代码一起使用的表,请在目录<JDBC tutorial directory>中运行以下命令:

ant setup

This command runs several Ant targets, including the following, build-tables (from the build.xml file):此命令运行多个Ant目标,包括以下build-tables(来自build.xml文件):

<target name="build-tables"
  description="Create database tables">
  <sql
    driver="${DB.DRIVER}"
    url="${DB.URL}"
    userid="${DB.USER}"
    password="${DB.PASSWORD}"
    classpathref="CLASSPATH"
    delimiter="${DB.DELIMITER}"
    autocommit="false" onerror="abort">
    <transaction src=
  "./sql/${DB.VENDOR}/create-tables.sql"/>
  </sql>
</target>

The sample specifies values for the following sql Ant task parameters:此示例指定以下sql Ant任务参数的值:

Parameter参数 Description描述
driver Fully qualified class name of your JDBC driver. JDBC驱动程序的完全限定类名。This sample uses org.apache.derby.jdbc.EmbeddedDriver for Java DB and com.mysql.cj.jdbc.Driver for MySQL Connector/J.此示例使用针对Java DB的org.apache.derby.jdbc.EmbeddedDriver和针对mysql Connector/J的com.mysql.cj.jdbc.Driver
url Database connection URL that your DBMS JDBC driver uses to connect to a database.DBMS JDBC驱动程序用于连接数据库的数据库连接URL。
userid Name of a valid user in your DBMS.DBMS中有效用户的名称。
password Password of the user specified in useriduserid中指定的用户的密码
classpathref Full path name of the JAR file that contains the class specified in driver包含driver中指定类的JAR文件的完整路径名
delimiter String or character that separates SQL statements. 分隔SQL语句的字符串或字符。This sample uses the semicolon (;).此示例使用分号(;)。
autocommit Boolean value; if set to false, all SQL statements are executed as one transaction.布尔值;如果设置为false,则所有SQL语句将作为一个事务执行。
onerror Action to perform when a statement fails; possible values are continue, stop, and abort. 语句失败时要执行的操作;可能的值有continuestopabortThe value abort specifies that if an error occurs, the transaction is aborted.abort指定如果发生错误,事务将中止。

The sample stores the values of these parameters in a separate file. 该示例将这些参数的值存储在单独的文件中。The build file build.xml retrieves these values with the import task:生成文件build.xml通过import任务检索以下值:

<import file="${ANTPROPERTIES}"/>

The transaction element specifies a file that contains SQL statements to execute. transaction元素指定包含要执行的SQL语句的文件。The file create-tables.sql contains SQL statements that create all the tables described on this page. 文件create-tables.sql包含创建此页上描述的所有表的sql语句。For example, the following excerpt from this file creates the tables SUPPLIERS and COFFEES:例如,此文件的以下摘录创建了SUPPLIERSCOFFEES表:

create table SUPPLIERS
    (SUP_ID integer NOT NULL,
    SUP_NAME varchar(40) NOT NULL,
    STREET varchar(40) NOT NULL,
    CITY varchar(20) NOT NULL,
    STATE char(2) NOT NULL,
    ZIP char(5),
    PRIMARY KEY (SUP_ID));

create table COFFEES
    (COF_NAME varchar(32) NOT NULL,
    SUP_ID int NOT NULL,
    PRICE numeric(10,2) NOT NULL,
    SALES integer NOT NULL,
    TOTAL integer NOT NULL,
    PRIMARY KEY (COF_NAME),
    FOREIGN KEY (SUP_ID)
        REFERENCES SUPPLIERS (SUP_ID));

Note: The file build.xml contains another target named drop-tables that deletes the tables used by the tutorial. :文件build.xml包含另一个名为drop-tables的目标,该目标删除教程使用的表。The setup target runs drop-tables before running the build-tables target.setup目标在运行drop-tables目标之前运行drop-tables

Creating Tables with JDBC API使用JDBC API创建表

The following method, SuppliersTable.createTable, creates the SUPPLIERS table:以下方法SuppliersTable.createTable创建SUPPLIERS表:

public void createTable() throws SQLException {
    String createString =
      "create table SUPPLIERS " + "(SUP_ID integer NOT NULL, " +
      "SUP_NAME varchar(40) NOT NULL, " + "STREET varchar(40) NOT NULL, " +
      "CITY varchar(20) NOT NULL, " + "STATE char(2) NOT NULL, " +
      "ZIP char(5), " + "PRIMARY KEY (SUP_ID))";
    
    try (Statement stmt = con.createStatement()) {
      stmt.executeUpdate(createString);
    } catch (SQLException e) {
      JDBCTutorialUtilities.printSQLException(e);
    }
  }

The following method, CoffeesTable.createTable, creates the COFFEES table:以下方法CoffeesTable.createTable创建COFFEES表:

public void createTable() throws SQLException {
    String createString =
      "create table COFFEES " + "(COF_NAME varchar(32) NOT NULL, " +
      "SUP_ID int NOT NULL, " + "PRICE numeric(10,2) NOT NULL, " +
      "SALES integer NOT NULL, " + "TOTAL integer NOT NULL, " +
      "PRIMARY KEY (COF_NAME), " +
      "FOREIGN KEY (SUP_ID) REFERENCES SUPPLIERS (SUP_ID))";
    try (Statement stmt = con.createStatement()) {
      stmt.executeUpdate(createString);
    } catch (SQLException e) {
      JDBCTutorialUtilities.printSQLException(e);
    }
  }

In both methods, con is a Connection object and dbName is the name of the database in which you are creating the table.在这两种方法中,con都是连接对象,dbName是创建表的数据库的名称。

To execute the SQL query, such as those specified by the String createString, use a Statement object. 要执行SQL查询,例如由字符串createString指定的查询,请使用Statement对象。To create a Statement object, call the method Connection.createStatement from an existing Connection object. 要创建Statement对象,请从现有Connection对象调用Connection.createStatement方法。To execute a SQL query, call the method Statement.executeUpdate.要执行SQL查询,请调用方法Statement.executeUpdate

All Statement objects are closed when the connection that created them is closed. 创建Statement对象的连接关闭时,所有语句对象都将关闭。However, it is good coding practice to explicitly close Statement objects as soon as you are finished with them. 但是,一完成Statement对象,就显式关闭它们是一种很好的编码实践。This allows any external resources that the statement is using to be released immediately. 这允许立即释放语句使用的任何外部资源。Close a statement by calling the method Statement.close. 通过调用方法Statement.close关闭语句。Place this statement in a finally to ensure that it closes even if the normal program flow is interrupted because an exception (such as SQLException) is thrown.将此语句放在finally中,以确保即使正常程序流因引发异常(如SQLException)而中断,它也会关闭。

Note: You must create the SUPPLIERS table before the COFFEES because COFFEES contains a foreign key, SUP_ID that references SUPPLIERS.:您必须在COFFEES之前创建SUPPLIERS表,因为COFFEES包含引用COFFEES的外键SUP_ID

Populating Tables填充表

Similarly, you can insert data into tables with Apache Ant or JDBC API.类似地,您可以使用ApacheAnt或JDBCAPI将数据插入表中。

Populating Tables with Apache Ant使用Apache Ant填充表

In addition to creating the tables used by this tutorial, the command ant setup also populates these tables. 除了创建本教程使用的表外,命令ant setup还填充这些表。This command runs the Ant target populate-tables, which runs the SQL script populate-tables.sql.此命令运行Ant目标populate-tables,该表运行SQL脚本populate-tables.sql

The following is an excerpt from populate-tables.sql that populates the tables SUPPLIERS and COFFEES:以下是从populate-tables.sql中摘录的内容,用于填充SUPPLIERSCOFFEES

insert into SUPPLIERS values(
    49, 'Superior Coffee', '1 Party Place',
    'Mendocino', 'CA', '95460');
insert into SUPPLIERS values(
    101, 'Acme, Inc.', '99 Market Street',
    'Groundsville', 'CA', '95199');
insert into SUPPLIERS values(
    150, 'The High Ground',
    '100 Coffee Lane', 'Meadows', 'CA', '93966');
insert into COFFEES values(
    'Colombian', 00101, 7.99, 0, 0);
insert into COFFEES values(
    'French_Roast', 00049, 8.99, 0, 0);
insert into COFFEES values(
    'Espresso', 00150, 9.99, 0, 0);
insert into COFFEES values(
    'Colombian_Decaf', 00101, 8.99, 0, 0);
insert into COFFEES values(
    'French_Roast_Decaf', 00049, 9.99, 0, 0);

Populating Tables with JDBC API用JDBCAPI填充表

The following method, SuppliersTable.populateTable, inserts data into the table:以下方法SuppliersTable.populateTable将数据插入表中:

public void populateTable() throws SQLException {
    try (Statement stmt = con.createStatement()) {
      stmt.executeUpdate("insert into SUPPLIERS " +
                         "values(49, 'Superior Coffee', '1 Party Place', " +
                         "'Mendocino', 'CA', '95460')");
      stmt.executeUpdate("insert into SUPPLIERS " +
                         "values(101, 'Acme, Inc.', '99 Market Street', " +
                         "'Groundsville', 'CA', '95199')");
      stmt.executeUpdate("insert into SUPPLIERS " +
                         "values(150, 'The High Ground', '100 Coffee Lane', " +
                         "'Meadows', 'CA', '93966')");
    } catch (SQLException e) {
      JDBCTutorialUtilities.printSQLException(e);
    }
  }

The following method, CoffeesTable.populateTable, inserts data into the table:以下方法CoffeesTable.populateTable将数据插入表中:

public void populateTable() throws SQLException {
    try (Statement stmt = con.createStatement()) {
      stmt.executeUpdate("insert into COFFEES " +
                         "values('Colombian', 00101, 7.99, 0, 0)");
      stmt.executeUpdate("insert into COFFEES " +
                         "values('French_Roast', 00049, 8.99, 0, 0)");
      stmt.executeUpdate("insert into COFFEES " +
                         "values('Espresso', 00150, 9.99, 0, 0)");
      stmt.executeUpdate("insert into COFFEES " +
                         "values('Colombian_Decaf', 00101, 8.99, 0, 0)");
      stmt.executeUpdate("insert into COFFEES " +
                         "values('French_Roast_Decaf', 00049, 9.99, 0, 0)");
    } catch (SQLException e) {
      JDBCTutorialUtilities.printSQLException(e);
    }
  }

Previous page: Handling SQLExceptions
Next page: Retrieving and Modifying Values from Result Sets