h2 does not enforce NOT NULL in MySQL compatibility mode

不问归期 提交于 2019-12-01 00:02:53

问题


In MySQL compatibility mode, the following SQL succeeds and returns 0:

CREATE TABLE test2 (i INTEGER NOT NULL);
INSERT INTO test2 VALUES (NULL);
SELECT * FROM test2;

It fails as expected in the default mode. It also fails with MySQL 5.5 / InnoDB. Does "MySQL compatibility" actually mean "MyISAM compatibility"?


回答1:


This problem is due to both the way MySQL handles Null values and h2. Basically MySQL converts nulls received to empty string/0 where as in h2 there is clear distinction among all three types.

So, they(h2) have decided to convert the nulls to 0/empty string/current time stamp in MYSQL mode. But since the as per core h2 0/empty string are not nulls, so it inserts the data.

Use org.h2.engine.Mode and modify the variable related to this:

Mode mode = Mode.getInstance("MYSQL");
mode.convertInsertNullToZero = false;

This has worked for me. Thanks to this link.




回答2:


From H2: MySQL Compatibility Mode:

When inserting data, if a column is defined to be NOT NULL and NULL is inserted, then a 0 (or empty string, or the current timestamp for timestamp columns) value is used. Usually, this operation is not allowed and an exception is thrown.

The MySQL manual says the following about INSERT, with no distinction between MyISAM or InnoDB:

Inserting NULL into a column that has been declared NOT NULL. For multiple-row INSERT statements [..], the column is set to the implicit default value for the column data type. [..] (For a single-row INSERT, no warning occurs when NULL is inserted into a NOT NULL column. Instead, the statement fails with an error.)

Thus I'm not sure why, or from whence, this choice was made by H2.



来源:https://stackoverflow.com/questions/20013154/h2-does-not-enforce-not-null-in-mysql-compatibility-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!