mysql数据库设置了一个id字段是自增的,但是插入数据时还是要手动插入id,不插入id就会出错。

2024-11-30 15:29:23
推荐回答(2个)
回答1:

成功的执行例子如下,仅供参考.

mysql> CREATE TABLE test_create_tab2 (
-> id INT AUTO_INCREMENT,
-> val VARCHAR(10),
-> PRIMARY KEY (id)
-> );
Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO test_create_tab2(val) VALUES ('NO id');
Query OK, 1 row affected (0.03 sec)

mysql> select last_insert_id() as id;
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)

mysql> INSERT INTO test_create_tab2(val) VALUES ('NO id 2');
Query OK, 1 row affected (0.03 sec)

mysql> select last_insert_id() as id;
+----+
| id |
+----+
| 2 |
+----+
1 row in set (0.00 sec)

mysql> select * from test_create_tab2;
+----+---------+
| id | val |
+----+---------+
| 1 | NO id |
| 2 | NO id 2 |
+----+---------+
2 rows in set (0.00 sec)

回答2:

主键ID设为not null auto_increment 然后插入的时候ID 那个字段填null 这样就好了