MySQL Inserts record with NULL value in NOT NULL column

后端 未结 3 1657
孤城傲影
孤城傲影 2020-12-09 19:38

Why does the first INSERT go through for table2. Note that table2.col_1 is NOT NULL. It doesn\'t insert NULL for col_1, but mysteriously converts the NULL value to an empty

相关标签:
3条回答
  • 2020-12-09 20:11

    You have MySQL's STRICT mode OFF. Turn it on and you'll get an error.

    Otherwise you can test for those warnings with PDO via: http://php.net/manual/en/pdo.errorinfo.php

    0 讨论(0)
  • 2020-12-09 20:23

    This behavior is well documented in MySQL docs . MySQL doc

    If you are not using strict mode, then whenever you insert an “incorrect” value into a column, such as a NULL into a NOT NULL column or a too-large numeric value into a numeric column, MySQL sets the column to the “best possible value” instead of producing an error:,but the warning count is incremented

    0 讨论(0)
  • 2020-12-09 20:27

    I have tried setting MySQL's STRICT mode OFF and didn't work for me (I even changed it to "my.ini" ).

    What worked for me was a BEFORE INSERT TRIGGER

    Basically you do:

    CREATE TRIGGER triggerName BEFORE INSERT ON customer
    FOR EACH ROW
    BEGIN
        if new.`customerName` = '' then
        signal sqlstate '45000'
        SET MESSAGE_TEXT = 'Customer Name Cannot be Empty!';
        end if;
    END
    

    In the MESSAGE_TEXT you can add whatever text you want the error to show.

    Hope it helps!

    Most of it found here

    0 讨论(0)
提交回复
热议问题