如何使用 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://127.0.0.1/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)
广告