Empty string inserting a zero, not a null

前端 未结 4 1349
一整个雨季
一整个雨季 2021-02-14 07:42

My insert statement looks like this:

INSERT INTO foo (bar) VALUES (\'\');

The bar field was created like so:

bar I         


        
相关标签:
4条回答
  • 2021-02-14 08:18

    You're not inserting NULL into the table; you're inserting an empty string (which apparently maps to zero as an int). Remember that NULL is a distinct value in SQL; NULL != ''. By specifying any value (other than NULL), you're not inserting NULL. The default only gets used if you don't specify a value; in your example, you specified a string value to an integer column.

    0 讨论(0)
  • 2021-02-14 08:34

    MySQL by default attempts to coerce invalid values for a column to the correct type. Here, the empty string '' is of type string, which is neither an integer nor NULL. I suggest taking the following steps:

    1. Change the query to the following: INSERT INTO foo (bar) VALUES (NULL);
    2. Enable strict mode in MySQL. This prevents as many unexpected type and value conversions from occurring. You will see more error messages when you try to do something MySQL doesn't expect, which helps you to spot problems more quickly.
    0 讨论(0)
  • 2021-02-14 08:36

    Why should it be a NULL? You're providing a value that has an integer representation: empty strings convert to INT 0.

    Only if you didn't provide any value would the default take over.

    0 讨论(0)
  • 2021-02-14 08:38

    The way to do this is to not fill the field at all. only fill the ones that actually need to have a value.

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