如何将 BOOL 值插入 MySQL 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13259654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:24:40  来源:igfitidea点击:

How to Insert BOOL Value to MySQL Database

mysql

提问by user1760110

I am trying to insert values into a BOOLdata type in MySQL (v 5.5.20) using the following script:

我正在尝试BOOL使用以下脚本将值插入MySQL (v 5.5.20) 中的数据类型:

CREATE DATABASE DBTest;
USE DBTest;
DROP TABLE IF EXISTS first;
CREATE TABLE first (id INT AUTO_INCREMENT NOT NULL PRIMARY KEY , name VARCHAR(30) ,sale  BOOL,); 
INSERT INTO first VALUES ("", "G22","TRUE");
INSERT INTO first VALUES ("", "G23","FALSE");

But the INSERTstatement just inserts 0(Zero) to the boolean column for both TRUEand FALSEoptions! Can you please let me know why this is happening?

但是该 INSERT语句只是将0(零)插入到布尔列TRUEFALSE选项中!你能告诉我为什么会这样吗?

回答by Michael Berkowski

TRUEand FALSEare keywords, and should not be quoted as strings:

TRUEandFALSE是关键字,不应作为字符串引用:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INTin MySQL), which translates into zero for any non-numeric string. Thus, you get 0for both values in your table.

通过将它们作为字符串引用,MySQL 会将它们转换为等效的整数(因为布尔值INT在 MySQL中实际上只是一个字节),对于任何非数字字符串,它都会转换为零。因此,您将获得0表中的两个值。

Non-numeric strings cast to zero:

非数字字符串强制转换为零:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INTrepresentation:

但是关键字返回它们对应的INT表示:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for idwith NULL. The empty string may issue a warning.

另请注意,我已将双引号替换为单引号,就像更标准的 SQL 字符串外壳一样。最后,我已经取代你的空字符串为idNULL。空字符串可能会发出警告。