如何使用 JDBC 在 MySQL 中建立一個帶自增列的表?


在某些情況下,在建立表時,我們需要使列值(如 ID)自動生成/遞增。不同的資料庫以不同的方式支援此功能。

MySQL 資料庫中,可以使用以下語法來宣告一個列自增。

CREATE TABLE table_name(
   ID INT PRIMARY KEY AUTO_INCREMENT,
   column_name1 data_type1,
   column_name2 data_type2,
   column_name3 data_type3,
   column_name4 data_type4,
   ............ ...........
);

MySQL 查詢以建立一個帶有自增列的表。

CREATE TABLE Sales(
   ID INT PRIMARY KEY AUTO_INCREMENT,
   ProductName VARCHAR (20) NOT NULL,
   CustomerName VARCHAR (20) NOT NULL,
   DispatchDate date,
   DeliveryTime timestamp,
   Price INT,
   Location varchar(20)
);

示例

下面的 JDBC 程式建立了與 MYSQL 資料庫的連線,並建立了一個帶有自增列的查詢。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class AutoIncrementedColumns_Oracle {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql:///mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Creating the sales table with auto-incremented values
      String createQuery = "CREATE TABLE Sales("
         + "ID INT PRIMARY KEY AUTO_INCREMENT, "
         + "ProductName VARCHAR (20) NOT NULL, "
         + "CustomerName VARCHAR (20) NOT NULL, "
         + "DispatchDate date, "
         + "DeliveryTime timestamp, "
         + "Price INT, "
         + "Location varchar(20))";
      //Executing the query
      stmt.execute(createQuery);
      System.out.println("Table created......");
   }
}

輸出

Connection established......
Table created......

驗證

MYSQL 中的 DESCRIBE 命令會提供表的描述,你可以使用它來驗證帶有自增列的表的建立,如下所示 −

mysql> describe sales;
+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| ID           | int(11)     | NO   | PRI | NULL    | auto_increment |
| ProductName  | varchar(20) | NO   |     | NULL    |                |
| CustomerName | varchar(20) | NO   |     | NULL    |                |
| DispatchDate | date        | YES  |     | NULL    |                |
| DeliveryTime | time        | YES  |     | NULL    |                |
| Price        | int(11)     | YES  |     | NULL    |                |
| Location     | varchar(20) | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)

更新於: 2020-6-29

2 千次以上瀏覽

啟動你的事業

完成課程以獲得認證

立即開始
廣告
© . All rights reserved.