proper way of inserting data with id as auto-increment in mysqli

后端 未结 3 937
予麋鹿
予麋鹿 2020-12-21 06:20

can someone please verify the proper way of inserting data using MYSQLI?

i need to insert comment data into the table with ID set as auto-increment. do i just leave

3条回答
  •  没有蜡笔的小新
    2020-12-21 07:04

    For an auto-increment column, you can omit it from the column list, and it will generate a new auto-increment value. You do this as @YourCommonSense showed, by specifying all columns except for the auto-increment column:

    INSERT INTO comments (comment) VALUES ('comment')
    

    For what it's worth, MySQL does the same thing if you specify 0 or NULL or DEFAULT for the auto-increment column.

    Below is an example test:

    mysql> select version();
    +---------------+
    | version()     |
    +---------------+
    | 5.6.13-56-log |
    +---------------+
    
    mysql> select @@sql_mode;
    +--------------------------------------------+
    | @@sql_mode                                 |
    +--------------------------------------------+
    | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION |
    +--------------------------------------------+
    
    mysql> insert into comments values (0, 'comment1');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> insert into comments values (null, 'comment2');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> insert into comments values (default, 'comment3');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> select * from comments;
    +----+----------+
    | id | comment  |
    +----+----------+
    |  1 | comment1 |
    |  2 | comment2 |
    |  3 | comment3 |
    +----+----------+
    

提交回复
热议问题