简体   繁体   English

MySql:向空值添加非空约束传递?

[英]MySql: Adding not null constraint to column with null values passes?

I have a JUnit test for some mysql code which passes locally but fails when run on the server. 我对一些本地传递的mysql代码进行了JUnit测试,但在服务器上运行时失败了。 Locally I am using Windows 7 and the server is Ubuntu 14.04. 本地我使用的是Windows 7,服务器是Ubuntu 14.04。 Both are running MySql 5.6. 两者都运行MySql 5.6。

I have a char column with a null value and try and put a not null constraint on it. 我有一个带有null值的char列,并尝试在其上放置一个非null约束。 Locally this fails as it should but on the server I only get a warning but it passes and the null value is set to a empty string. 在本地,这应该失败,但在服务器上我只得到一个警告,但它通过,并将空值设置为空字符串。 (See images) I assume this is some difference in mysql server configuration? (见图)我假设这是mysql服务器配置的一些区别? I am new to MySql and can't find how to fix this. 我是MySql的新手,无法找到解决方法。

Example image: up is server, down is local: 示例图像:up是server,down是local:

示例图像:up是server,down是local

First check: 首先检查:

SELECT @@sql_mode;

You probably get: 你可能得到:

STRICT_TRANS_TABLES/STRICT_ALL_TABLES


UP env :   -------
DOWN env:   STRICT_..._TABLES

The difference is Error vs Warning : 区别在于错误与警告

在此输入图像描述

Modes : 模式

Strict mode controls how MySQL handles invalid or missing values in data-change statements such as INSERT or UPDATE. 严格模式控制MySQL如何处理数据更改语句(如INSERT或UPDATE)中的无效或缺失值。 A value can be invalid for several reasons. 由于多种原因,值可能无效。 For example, it might have the wrong data type for the column, or it might be out of range. 例如,列可能具有错误的数据类型,或者可能超出范围。 A value is missing when a new row to be inserted does not contain a value for a non-NULL column that has no explicit DEFAULT clause in its definition. 当要插入的新行不包含其定义中没有显式DEFAULT子句的非NULL列的值时,缺少值。 (For a NULL column, NULL is inserted if the value is missing.) (对于NULL列,如果缺少值,则插入NULL。)

SqlFiddleDemo

The correct way to solve it is first to update NULL to empty string before altering schema. 解决它的正确方法是首先在更改模式之前将NULL更新为空字符串。

CREATE TABLE test_table(primary_key INT AUTO_INCREMENT PRIMARY KEY,
                        short_char CHAR(100));

INSERT INTO test_table(short_char)
VALUES (NULL);

UPDATE test_table
SET short_char = ''
WHERE short_char IS NULL;

ALTER TABLE test_table modify short_char char(100) not null;

SqlFiddleDemo2

I recommend to use VARCHAR(100) instead of CHAR(100) . 我建议使用VARCHAR(100)而不是CHAR(100)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM