Ошибка 1364 mysql workbench

My table looks like create table try ( name varchar(8), CREATED_BY varchar(40) not null); and then I have a trigger to auto populate the CREATED_BY field create trigger autoPopulateAtInsert BEF...

My table looks like

create table try ( name varchar(8), CREATED_BY varchar(40) not null);

and then I have a trigger to auto populate the CREATED_BY field

create trigger autoPopulateAtInsert BEFORE INSERT on try for each row set new.CREATED_BY=user();

When I do an insert using

insert into try (name) values ('abc');

the entry is made in the table but I still get the error message

Field 'CREATED_BY' doesn't have a default value Error no 1364

Is there a way to suppress this error without making the field nullable AND without removing the triggfer? Otherwise my hibernate will see these exceptions ( even though the insertions have been made) and then application will crash.

Miklos Aubert's user avatar

asked Mar 15, 2013 at 17:41

kk1957's user avatar

Open phpmyadmin and goto ‘More’ Tab and select ‘Variables’ submenu.
Scroll down to find sql mode.
Edit sql mode and remove ‘STRICT_TRANS_TABLES’
Save it.

answered Oct 19, 2014 at 15:41

Nilesh Dhangare's user avatar

Nilesh DhangareNilesh Dhangare

1,0611 gold badge7 silver badges2 bronze badges

6

In phpmyadmin, perform the following:

select @@GLOBAL.sql_mode

In my case, I get the following:

ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES ,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Copy this result and remove STRICT_TRANS_TABLES. Then perform the following:

set GLOBAL sql_mode='ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

answered Aug 26, 2016 at 7:43

Kamil's user avatar

KamilKamil

8701 gold badge8 silver badges18 bronze badges

5

Set a default value for Created_By (eg: empty VARCHAR) and the trigger will update the value anyways.

create table try ( 
     name varchar(8), 
     CREATED_BY varchar(40) DEFAULT '' not null
);

zardilior's user avatar

zardilior

2,66224 silver badges29 bronze badges

answered Mar 15, 2013 at 17:47

KinSlayerUY's user avatar

KinSlayerUYKinSlayerUY

1,87316 silver badges22 bronze badges

8

When I had this same problem with mysql5.6.20 installed with Homebrew, I solved it by going into my.cnf

nano /usr/local/Cellar/mysql/5.6.20_1/my.cnf

Find the line that looks like so:

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

Comment above line out and restart mysql server

mysql.server restart

Error gone!

answered Sep 15, 2014 at 13:37

Kingsley Ijomah's user avatar

Run mysql console:

mysql -u your_username -p

, select database:

USE your_database;

and run (also from mysql console):

SET GLOBAL sql_mode='';

That will turn off strict mode and mysql won’t complain any more.

To make things clear: your database definition says «this field must have default value defined», and by doing steps from above you say to MySql «neah, just ignore it». So if you just want to do some quick fix locally this solution is ok. But generally you should investigate in your database definition and check if field really needs default value and if so set it. And if default value is not needed this requirement should be removed to have clean situation.

answered Aug 17, 2018 at 8:22

MilanG's user avatar

MilanGMilanG

6,9162 gold badges35 silver badges64 bronze badges

8

As others said, this is caused by the STRICT_TRANS_TABLES SQL mode.

To check whether STRICT_TRANS_TABLES mode is enabled:

SHOW VARIABLES LIKE 'sql_mode';

To disable strict mode:

SET GLOBAL sql_mode='';

answered Aug 24, 2018 at 12:35

Damjan Pavlica's user avatar

Damjan PavlicaDamjan Pavlica

29.6k8 gold badges69 silver badges76 bronze badges

3

Before every insert action I added below line and solved my issue,

SET SQL_MODE = '';

I’m not sure if this is the best solution,

SET SQL_MODE = ''; INSERT INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

answered Mar 22, 2017 at 17:12

Vinith's user avatar

VinithVinith

1,26614 silver badges25 bronze badges

2

Modify your query and add «IGNORE» as:

INSERT IGNORE INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

answered Feb 15, 2018 at 9:05

Rohit Dhiman's user avatar

3

Its work and tested Copy to Config File: /etc/mysql/my.cnf OR /bin/mysql/my.ini

[mysqld]
port = 3306
sql-mode=""

then restart MySQL

ddb's user avatar

ddb

2,4137 gold badges28 silver badges38 bronze badges

answered Aug 30, 2016 at 7:44

Devraj Gupta's user avatar

0

This appears to be caused by a long-standing (since 2004) bug (#6295) in MySQL, titled

Triggers are not processed for NOT NULL columns.

It was allegedly fixed in version 5.7.1 of MySQL (Changelog, last entry) in 2013, making MySQL behave as “per the SQL standard” (ibid).

answered Apr 24, 2015 at 17:52

B98's user avatar

B98B98

1,22912 silver badges20 bronze badges

3

For Windows WampServer users:

WAMP > MySQL > my.ini

search file for sql-mode=""

Uncomment it.

answered Apr 21, 2017 at 16:23

Andrew's user avatar

AndrewAndrew

17.8k12 gold badges102 silver badges112 bronze badges

1

In Windows Server edit my.ini (for example program filesmysqlmysql server n.nmy.ini)

I would not simply set the sql-mode=»», rather I suggest one removes STRICT_TRANS_TABLES from the line, leave everything as-was, and then restart MySQL from the services utility. Add a comment for future programmers who you are and what you did.

answered Dec 3, 2018 at 18:14

Bill Degnan's user avatar

2

Most of these answers are a lot of work for the not-seasoned coder. Like mentioned the issues is with STRICT_TRANS_TABLES.

First verify STRICT_TRANS_TABLES is running.

$ mysql -u root -p -e "SHOW VARIABLES LIKE 'sql_mode';"

You can disable strict mode on your MySQL server by running the following command on your Linode’s command line:

$ mysql -u root -p -e "SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';"

Then, you can verify that the mode is set by running the following:

$ mysql -u root -p -e "SELECT @@GLOBAL.sql_mode;"

This answer was found here https://www.linode.com/community/questions/17070/how-can-i-disable-mysql-strict-mode

answered Sep 30, 2022 at 21:24

themeowman 's user avatar

i set the fields to not null and problem solved, it updates when an information is commanded to store in it, no more showing msqli message that the field was empty cus you didnt insert value to it, well application of this solution can work on some projects depends on your project structure.

answered Nov 25, 2016 at 1:34

ExploreTech's user avatar

1

This is for SYNOLOGY device users:


  • How to set global variables (strict mode OFF) on SYNOLOGY device.
    (checked on DSM 7.0.1-42218 — device model DS418)

Used PUTTY to connect:
login as root and
sudo su after… (to be admin total)

  • if not exist create my.cnf in:

MariaDB 5:
/var/packages/MariaDB/etc
MariaDB 10:
/var/packages/MariaDB10/etc

  • this should be in the file (at least for strict mode off)
# custom configs
[mysqld]
innodb_strict_mode = OFF
sql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
  • restart mysqld daemon:
    MariaDB 5:
    /usr/syno/bin/synopkg restart MariaDB
    MariaDB 10:
    /usr/syno/bin/synopkg restart MariaDB10

  • check for strict mode enabled at these two global options — both should be not there or off (see config above)

  • log into mysql:
    mysql -u root -p

  • enter password:

show variables like ‘sql_mode’;
show variables like ‘%STRICT%’;


answered Jan 9, 2022 at 6:32

Peter Maly's user avatar

i solved problem changing my.ini file located in data folder. for mysql 5.6 my.ini file moved to data folder rather the bin or mysql installation folder.

answered Jun 2, 2019 at 9:58

sadik keskin's user avatar

I think in name column have null values in this case.

update try set name='abc' where created_by='def';
  

answered Jun 25, 2020 at 5:56

Sasindu's user avatar

I am using Xampp 7.3.28-1 for Linux. It uses MariaDB 10.4.19. Its configuration file is:
/opt/lampp/etc/my.cnf

It does NOT contain an entry that defines sql_mode.
However the query «select @@GLOBAL.sql_mode;» does return a result and it contains the problematic STRICT_TRANS_TABLES. I guess it is by default now.

My solution was to explicitly define the mode by adding this line below [mysqld]:
sql_mode=NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

You can define the modes that you need or just leave it blank.

answered Jun 17, 2021 at 19:05

M.Paunov's user avatar

M.PaunovM.Paunov

1,5971 gold badge13 silver badges19 bronze badges

I found that once I removed what was a doubling up of a foreign key and primary key, when I could have just used the foreign key as the primary key alone in the table. All my code then worked and I was able to upload to db.

answered Nov 21, 2021 at 10:34

Spinstaz's user avatar

SpinstazSpinstaz

2327 silver badges11 bronze badges

My table looks like

create table try ( name varchar(8), CREATED_BY varchar(40) not null);

and then I have a trigger to auto populate the CREATED_BY field

create trigger autoPopulateAtInsert BEFORE INSERT on try for each row set new.CREATED_BY=user();

When I do an insert using

insert into try (name) values ('abc');

the entry is made in the table but I still get the error message

Field 'CREATED_BY' doesn't have a default value Error no 1364

Is there a way to suppress this error without making the field nullable AND without removing the triggfer? Otherwise my hibernate will see these exceptions ( even though the insertions have been made) and then application will crash.

Miklos Aubert's user avatar

asked Mar 15, 2013 at 17:41

kk1957's user avatar

Open phpmyadmin and goto ‘More’ Tab and select ‘Variables’ submenu.
Scroll down to find sql mode.
Edit sql mode and remove ‘STRICT_TRANS_TABLES’
Save it.

answered Oct 19, 2014 at 15:41

Nilesh Dhangare's user avatar

Nilesh DhangareNilesh Dhangare

1,0611 gold badge7 silver badges2 bronze badges

6

In phpmyadmin, perform the following:

select @@GLOBAL.sql_mode

In my case, I get the following:

ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES ,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Copy this result and remove STRICT_TRANS_TABLES. Then perform the following:

set GLOBAL sql_mode='ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

answered Aug 26, 2016 at 7:43

Kamil's user avatar

KamilKamil

8701 gold badge8 silver badges18 bronze badges

5

Set a default value for Created_By (eg: empty VARCHAR) and the trigger will update the value anyways.

create table try ( 
     name varchar(8), 
     CREATED_BY varchar(40) DEFAULT '' not null
);

zardilior's user avatar

zardilior

2,66224 silver badges29 bronze badges

answered Mar 15, 2013 at 17:47

KinSlayerUY's user avatar

KinSlayerUYKinSlayerUY

1,87316 silver badges22 bronze badges

8

When I had this same problem with mysql5.6.20 installed with Homebrew, I solved it by going into my.cnf

nano /usr/local/Cellar/mysql/5.6.20_1/my.cnf

Find the line that looks like so:

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

Comment above line out and restart mysql server

mysql.server restart

Error gone!

answered Sep 15, 2014 at 13:37

Kingsley Ijomah's user avatar

Run mysql console:

mysql -u your_username -p

, select database:

USE your_database;

and run (also from mysql console):

SET GLOBAL sql_mode='';

That will turn off strict mode and mysql won’t complain any more.

To make things clear: your database definition says «this field must have default value defined», and by doing steps from above you say to MySql «neah, just ignore it». So if you just want to do some quick fix locally this solution is ok. But generally you should investigate in your database definition and check if field really needs default value and if so set it. And if default value is not needed this requirement should be removed to have clean situation.

answered Aug 17, 2018 at 8:22

MilanG's user avatar

MilanGMilanG

6,9162 gold badges35 silver badges64 bronze badges

8

As others said, this is caused by the STRICT_TRANS_TABLES SQL mode.

To check whether STRICT_TRANS_TABLES mode is enabled:

SHOW VARIABLES LIKE 'sql_mode';

To disable strict mode:

SET GLOBAL sql_mode='';

answered Aug 24, 2018 at 12:35

Damjan Pavlica's user avatar

Damjan PavlicaDamjan Pavlica

29.6k8 gold badges69 silver badges76 bronze badges

3

Before every insert action I added below line and solved my issue,

SET SQL_MODE = '';

I’m not sure if this is the best solution,

SET SQL_MODE = ''; INSERT INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

answered Mar 22, 2017 at 17:12

Vinith's user avatar

VinithVinith

1,26614 silver badges25 bronze badges

2

Modify your query and add «IGNORE» as:

INSERT IGNORE INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

answered Feb 15, 2018 at 9:05

Rohit Dhiman's user avatar

3

Its work and tested Copy to Config File: /etc/mysql/my.cnf OR /bin/mysql/my.ini

[mysqld]
port = 3306
sql-mode=""

then restart MySQL

ddb's user avatar

ddb

2,4137 gold badges28 silver badges38 bronze badges

answered Aug 30, 2016 at 7:44

Devraj Gupta's user avatar

0

This appears to be caused by a long-standing (since 2004) bug (#6295) in MySQL, titled

Triggers are not processed for NOT NULL columns.

It was allegedly fixed in version 5.7.1 of MySQL (Changelog, last entry) in 2013, making MySQL behave as “per the SQL standard” (ibid).

answered Apr 24, 2015 at 17:52

B98's user avatar

B98B98

1,22912 silver badges20 bronze badges

3

For Windows WampServer users:

WAMP > MySQL > my.ini

search file for sql-mode=""

Uncomment it.

answered Apr 21, 2017 at 16:23

Andrew's user avatar

AndrewAndrew

17.8k12 gold badges102 silver badges112 bronze badges

1

In Windows Server edit my.ini (for example program filesmysqlmysql server n.nmy.ini)

I would not simply set the sql-mode=»», rather I suggest one removes STRICT_TRANS_TABLES from the line, leave everything as-was, and then restart MySQL from the services utility. Add a comment for future programmers who you are and what you did.

answered Dec 3, 2018 at 18:14

Bill Degnan's user avatar

2

Most of these answers are a lot of work for the not-seasoned coder. Like mentioned the issues is with STRICT_TRANS_TABLES.

First verify STRICT_TRANS_TABLES is running.

$ mysql -u root -p -e "SHOW VARIABLES LIKE 'sql_mode';"

You can disable strict mode on your MySQL server by running the following command on your Linode’s command line:

$ mysql -u root -p -e "SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';"

Then, you can verify that the mode is set by running the following:

$ mysql -u root -p -e "SELECT @@GLOBAL.sql_mode;"

This answer was found here https://www.linode.com/community/questions/17070/how-can-i-disable-mysql-strict-mode

answered Sep 30, 2022 at 21:24

themeowman 's user avatar

i set the fields to not null and problem solved, it updates when an information is commanded to store in it, no more showing msqli message that the field was empty cus you didnt insert value to it, well application of this solution can work on some projects depends on your project structure.

answered Nov 25, 2016 at 1:34

ExploreTech's user avatar

1

This is for SYNOLOGY device users:


  • How to set global variables (strict mode OFF) on SYNOLOGY device.
    (checked on DSM 7.0.1-42218 — device model DS418)

Used PUTTY to connect:
login as root and
sudo su after… (to be admin total)

  • if not exist create my.cnf in:

MariaDB 5:
/var/packages/MariaDB/etc
MariaDB 10:
/var/packages/MariaDB10/etc

  • this should be in the file (at least for strict mode off)
# custom configs
[mysqld]
innodb_strict_mode = OFF
sql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
  • restart mysqld daemon:
    MariaDB 5:
    /usr/syno/bin/synopkg restart MariaDB
    MariaDB 10:
    /usr/syno/bin/synopkg restart MariaDB10

  • check for strict mode enabled at these two global options — both should be not there or off (see config above)

  • log into mysql:
    mysql -u root -p

  • enter password:

show variables like ‘sql_mode’;
show variables like ‘%STRICT%’;


answered Jan 9, 2022 at 6:32

Peter Maly's user avatar

i solved problem changing my.ini file located in data folder. for mysql 5.6 my.ini file moved to data folder rather the bin or mysql installation folder.

answered Jun 2, 2019 at 9:58

sadik keskin's user avatar

I think in name column have null values in this case.

update try set name='abc' where created_by='def';
  

answered Jun 25, 2020 at 5:56

Sasindu's user avatar

I am using Xampp 7.3.28-1 for Linux. It uses MariaDB 10.4.19. Its configuration file is:
/opt/lampp/etc/my.cnf

It does NOT contain an entry that defines sql_mode.
However the query «select @@GLOBAL.sql_mode;» does return a result and it contains the problematic STRICT_TRANS_TABLES. I guess it is by default now.

My solution was to explicitly define the mode by adding this line below [mysqld]:
sql_mode=NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

You can define the modes that you need or just leave it blank.

answered Jun 17, 2021 at 19:05

M.Paunov's user avatar

M.PaunovM.Paunov

1,5971 gold badge13 silver badges19 bronze badges

I found that once I removed what was a doubling up of a foreign key and primary key, when I could have just used the foreign key as the primary key alone in the table. All my code then worked and I was able to upload to db.

answered Nov 21, 2021 at 10:34

Spinstaz's user avatar

SpinstazSpinstaz

2327 silver badges11 bronze badges

Содержание

  1. MySQL Error 1364 | How To Resolve It?
  2. When will we see ‘MySQL Error 1364’?
  3. How To Fix MySQL Error 1364?
  4. Conclusion
  5. PREVENT YOUR SERVER FROM CRASHING!
  6. Error Code: 1364 [Solved] Field doesn’t have a default value
  7. Introduction
  8. Error code 1364 resolution with AUTO_INCREMENT
  9. Error code 1364 resolution with DEFAULT value
  10. Как решить MySQL исключение SQLSTATE [HY000]: Общая ошибка: 1364 Поле field_name не имеет значения по умолчанию
  11. А. Логическое решение
  12. Б. Серверное решение
  13. MySQL: ERROR1364 fix
  14. It’s all about the money
  15. Failing inserts
  16. Unusual debugging
  17. Field doesn’t have a default value
  18. Changing the configuration
  19. How to solve MySQL exception SQLSTATE[HY000]: General error: 1364 Field ‘field_name’ doesn’t have a default value
  20. A. Logic Solution
  21. B. Server Side Solution

MySQL Error 1364 | How To Resolve It?

by Shahalamol R | Aug 11, 2022

MySQL Error 1364 can now be fixed with any of these methods provided in this article. At Bobcares, as part of our MySQL Support Service, we answers all MySQL inquiries, large or small.

When will we see ‘MySQL Error 1364’?

If a query or statement tries to insert/update a record without a value for a specific column that is NOT NULL, MySQL server throws the Error 1364. We can say that the MySQL server throws this error because there wasn’t a NOT NULL column value during the insertion process.

This exception only occurs when using MySQL in Strict mode. We can find out easily what mode the MySQL server is running in by executing the following command:

How To Fix MySQL Error 1364?

Let’s see the ways our Support team suggests to fix this error.

    Logic Solution: When trying to insert a record, the value will be null but the error won’t be thrown if you provide a value for the field that is causing the exception or specify that the field can be null. For instance, with a column that cannot be null, the following query would throw the exception.

Now we alter the column to make the column nullable.

The MySQL Error 1364 will not appear again.

Now save the changes, restart MySQL, and the MySQL Error 1364 won’t show up again.

Here the columns, emp_id and emp_enroll_no both cannot be NULL. Then insert a record with the command without specifying any value for column emp_id.

Since we left emp_id blank in the insert statement, the output reveals the MySQL Error 1364 with the following message response: Error Code 1364. So we can fix it by ALTER query. Any insert after executing the below statement will assign a value to emp_id starting with 1 and increments by 1 in successive inserts.

Now executing the insert statement again without specifying any value for column emp_id will result in a successful insert this time.

[Looking for a solution to another query? We are just a click away.]

Conclusion

To conclude, Our Support team briefly explains about the MySQL Error 1364. The article also includes some of the simple solutions to fix the error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

Источник

Error Code: 1364 [Solved] Field doesn’t have a default value

In this article, we will discuss why Error 1364 occurs and how to resolve it.

Table of Contents

Introduction

MySQL server throws the Error 1364 if the query or statement tries to insert a row without a value for a particular column defined as NOT NULL. We can say that the absence of a NOT NULL column value during insertion causes this error to be thrown by the MySQL server.

Error 1364 indicates that the value of the particular field should be something other than NULL. One way to resolve the error forever is to make the column as DEFAULT NULL in table definition but if that does not meet your requirement, let us see some ways to fix this error in the below sections.

We will be creating a sample table employee_details for illustration of the concept.

Here, the column emp_id and emp_enroll_no both cannot be NULL.

Output:-

Error code 1364 resolution with AUTO_INCREMENT

In this section, we will recreate error 1364 and will fix it using the AUTO_INCREMENT keyword. AUTO_INCREMENT in MySQL assigns a numeric value to a column starting from 1 (when another starting number not specified) and then increments the value by 1 for consecutive inserts.

Let us try to insert a row without specifying any value for column emp_id.

Action Output:-

Since we did not specify any value for emp_id in the insert statement, the output in image_2 shows that the error 1364 is thrown with the message response: Error Code: 1364. Field ’emp_id’ doesn’t have a default value.

Observe the below ALTER query for the solution. Any insert happening after executing the below statement will assign a value to emp_id starting with 1 and incremented by 1 in successive inserts.

Action Output:-

Let us again try to execute the insert statement.

Action Output:-

Insert is successful this time.

Output:-

Error code 1364 resolution with DEFAULT value

This section will recreate error 1364 and fix it by assigning a DEFAULT value to the column.

Let us try to insert a row without specifying any value for column emp_enroll_no.

Action Output:-

Since we did not specify any value for emp_enroll_no in the insert statement, the output in image_6 shows that the error 1364 is thrown with the message response: Error Code: 1364. Field ’emp_enroll_no’ doesn’t have a default value .

Observe the below ALTER query for the solution. Here, we will give a default value to the column emp_enroll_no such that if any insert happens without any value for emp_enroll_no, a default value “N-N” will be inserted.

Action Output:-

Let us again try to execute the same insert statement.

Action Output:-

Insert is successful this time.

Output:-

The output in image_9 shows that a default value of “N-N” was inserted in second row.

READ MORE:

We hope this article helped you understand and resolve Error 1364 in MySQL. Good Luck.

Источник

Как решить MySQL исключение SQLSTATE [HY000]: Общая ошибка: 1364 Поле field_name не имеет значения по умолчанию

Общая ошибка 1364 в основном возникает, когда вы пытаетесь вставить / обновить запись в вашей базе данных, где поле, а именно то, которое вызывает исключение, не может быть нулевым, однако вы пытаетесь установить его значение как нулевое (вы не предоставляя значение для этого). Обычно это исключение срабатывает только при использовании MySQL в строгом режиме, Вы можете получить режим, который использует ваш сервер MySQL, с помощью следующего запроса:

Если вы столкнулись с этим исключением, возможно, потому что у вас включен строгий режим ( STRICT_TRANS_TABLES ). В этой статье мы расскажем вам о двух способах предотвращения появления этого исключения.

А. Логическое решение

Чтобы предотвратить это исключение, просто предоставьте значение для поля, которое вызывает исключение, или определите, что поле может быть пустым, поэтому при попытке вставить запись значение будет нулевым, но ошибка не будет выдана, для Например, со столбцом, который не может быть пустым, следующий запрос выдаст исключение:

Таким образом, вы можете изменить столбец, чтобы сделать его обнуляемым:

И это все, исключение больше не должно появляться.

Б. Серверное решение

Если вы не можете самостоятельно определить значение столбца, потому что вы используете платформу или другой тип логики, которая сначала вставляет запись с нулевым значением, а затем обновляется, вы можете положиться на простой способ, который удаляет строгий режим MySQL. Это в некоторой степени не рекомендуется, так как это предотвращает, например, вставку пустого значения в столбец, который не может быть пустым, вызывая упомянутое исключение. Все происходит в основном как мера контроля, которая предотвращает сбой вашей логики и предотвращает написание нестабильного кода, где вы можете упустить неправильную написанную логику и т. Д.

В других случаях написанная вами логика работает в вашей локальной среде, потому что, вероятно, вы не установили там строгий режим, но на вашем рабочем сервере он не работает из-за этого режима. В этом случае вы можете отключить строгий режим, изменив конфигурационный файл MySQL ( my.ini в Windows или my.cnf в Linux) установка sql_mode в пустую строку или удаление STRICT_TRANS_TABLES опция, которая устанавливает MySQL в строгом режиме и имеет NO_ENGINE_SUBSTITUTION режим включен:

Сохраните изменения, перезапустите службу mysql, и ошибка больше не будет появляться, вместо этого для столбца будет установлено значение null, хотя это не разрешено.

Источник

MySQL: ERROR1364 fix

It’s all about the money

Saving $s has become a hard fact for many individuals and companies these days. In this process I started questioning whether I really need an AWS RDS database instance of whether I run my mysql installation on my EC2. After a rather simple switch, I set up a cron-job for dumps and planned on storing them in a separate S3 bucket (you never know, right?).

The complete process took me less than two hours and I started to rethink some DevOps concepts after being very happy with the benchmarks & performance of my brave EC2 micro instance.

Failing inserts

However, something was off. Did people stop using the POC installation of blua.blue? Since I am a big proponent of privacy, monitoring is limited to a minimum. But API traffic seemed normal.

I tried logging in, changing settings, signing up, commenting, viewing — all seemed working. Until I failed to create a new article.

Unusual debugging

I was unable to reproduce the error locally and none of the error logs on my server showed anything. Hm, how was my error reporting set up again? Sometimes the bold methods are the right choice: I logged every SQL-transaction result and found the following error-number on some transactions: 1364

Field doesn’t have a default value

A quick google search revealed that apparently some of my tables contain columns requiring a value. But didn’t I use exactly the same schemata as previously used via RDS? Thankfully, I am not the first one running into this issue and it seemed I should check somewhere else then I expected: in my MySQL configuration. The fist thing I did was verifying that what I read online is indeed my problem:

Exit fullscreen mode

And sure enough, there it was: STRICT_TRANS_TABLES

What this variable does is setting the your MySQL to reject any empty (or most likely undefined) field or your query unless there is a defined default value.
I don’t know about you, but I always lived quite happily with the fact that nullable fields will default to null. And minimizing constraints is definitely a plus on top of the laziness.
So how can I get rid of that behavior?

Changing the configuration

The easiest way is to override your mysql configuration. Depending on your setup, your will find various .cnf files that will offer possibilities. If you are not sure, simply create a new one in the conf-directory (likely /etc/mysql/conf.d/ ).

Here are the steps to take:

  1. copy your existing mode-variable (see above SQL-query)
  2. define your new sql_mode variable (under mysqld block)
  3. restart the mysql service

If you created your own .cnf-file (e.g. custom.cnf ), it could now look like this:

Exit fullscreen mode

After restarting your service, you might want to check your setup again

$ sudo service mysql restart

$ mysql -u root -p
mysql> SHOW VARIABLES LIKE ‘sql_mode’;

Источник

How to solve MySQL exception SQLSTATE[HY000]: General error: 1364 Field ‘field_name’ doesn’t have a default value

Carlos Delgado

Learn why this exception is thrown in MySQL and how to bypass it.

The general error 1364 is basically triggered when you are try to insert/update a record on your database where a field, namely the one that is triggering the exception cannot be null, however you are trying to set its value as null (you are not providing a value for it). Normally, this exception is only triggered when you are using MySQL in Strict mode, you can get the mode that your MySQL server is using with the following query:

If you face this exception, it’s probably because you have the strict mode enabled ( STRICT_TRANS_TABLES ). In this article, we’ll share with you 2 ways to prevent this exception from appearing easily.

A. Logic Solution

To prevent this exception, simply provide a value for the field that is triggering the exception or define that the field can be null, so when you try to insert a record, the value will be null but the error won’t be thrown, for example with a column that cannot be null, the following query would throw the exception:

So you could alter the column to make the column nullable:

And that’s it, the exception shouldn’t appear anymore.

B. Server Side Solution

If you are unable to define by yourself the value of the column because you are using a framework or other kind of logic that first inserts the record with null and then it’s updated, you may rely on the easy way that is removing the strict mode of MySQL. This is someway not recommended as this prevents for example the insertion of an empty value in a column that cannot be null throwing the mentioned exception. All happens basically as a measure of control that prevents that your logic fails and prevents you from writing flappy code, where you may overlook wrong written logic etc.

In other cases, the logic that you wrote works on your local environment, because probably you don’t have set the strict mode in there, but on your production server it doesn’t work because of this mode. In this case, you can disable the strict mode modifying the configuration file of MySQL ( my.ini in Windows or my.cnf in Linux) setting the sql_mode to an empty string or removing the STRICT_TRANS_TABLES option that sets MySQL in Strict Mode and having the NO_ENGINE_SUBSTITUTION mode enabled:

Save changes, restart the mysql service and the error won’t appear anymore, instead the column will be set to null although it’s not allowed.

Источник

My table looks like

create table try ( name varchar(8), CREATED_BY varchar(40) not null);

and then I have a trigger to auto populate the CREATED_BY field

create trigger autoPopulateAtInsert BEFORE INSERT on try for each row set new.CREATED_BY=user();

When I do an insert using

insert into try (name) values ('abc');

the entry is made in the table but I still get the error message

Field 'CREATED_BY' doesn't have a default value Error no 1364

Is there a way to suppress this error without making the field nullable AND without removing the triggfer? Otherwise my hibernate will see these exceptions ( even though the insertions have been made) and then application will crash.

Miklos Aubert's user avatar

asked Mar 15, 2013 at 17:41

kk1957's user avatar

Open phpmyadmin and goto ‘More’ Tab and select ‘Variables’ submenu.
Scroll down to find sql mode.
Edit sql mode and remove ‘STRICT_TRANS_TABLES’
Save it.

answered Oct 19, 2014 at 15:41

Nilesh Dhangare's user avatar

Nilesh DhangareNilesh Dhangare

1,0611 gold badge7 silver badges2 bronze badges

6

In phpmyadmin, perform the following:

select @@GLOBAL.sql_mode

In my case, I get the following:

ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES ,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Copy this result and remove STRICT_TRANS_TABLES. Then perform the following:

set GLOBAL sql_mode='ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

answered Aug 26, 2016 at 7:43

Kamil's user avatar

KamilKamil

8701 gold badge8 silver badges18 bronze badges

5

Set a default value for Created_By (eg: empty VARCHAR) and the trigger will update the value anyways.

create table try ( 
     name varchar(8), 
     CREATED_BY varchar(40) DEFAULT '' not null
);

zardilior's user avatar

zardilior

2,66224 silver badges29 bronze badges

answered Mar 15, 2013 at 17:47

KinSlayerUY's user avatar

KinSlayerUYKinSlayerUY

1,87316 silver badges22 bronze badges

8

When I had this same problem with mysql5.6.20 installed with Homebrew, I solved it by going into my.cnf

nano /usr/local/Cellar/mysql/5.6.20_1/my.cnf

Find the line that looks like so:

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

Comment above line out and restart mysql server

mysql.server restart

Error gone!

answered Sep 15, 2014 at 13:37

Kingsley Ijomah's user avatar

Run mysql console:

mysql -u your_username -p

, select database:

USE your_database;

and run (also from mysql console):

SET GLOBAL sql_mode='';

That will turn off strict mode and mysql won’t complain any more.

To make things clear: your database definition says «this field must have default value defined», and by doing steps from above you say to MySql «neah, just ignore it». So if you just want to do some quick fix locally this solution is ok. But generally you should investigate in your database definition and check if field really needs default value and if so set it. And if default value is not needed this requirement should be removed to have clean situation.

answered Aug 17, 2018 at 8:22

MilanG's user avatar

MilanGMilanG

6,9162 gold badges35 silver badges64 bronze badges

8

As others said, this is caused by the STRICT_TRANS_TABLES SQL mode.

To check whether STRICT_TRANS_TABLES mode is enabled:

SHOW VARIABLES LIKE 'sql_mode';

To disable strict mode:

SET GLOBAL sql_mode='';

answered Aug 24, 2018 at 12:35

Damjan Pavlica's user avatar

Damjan PavlicaDamjan Pavlica

29.6k8 gold badges69 silver badges76 bronze badges

3

Before every insert action I added below line and solved my issue,

SET SQL_MODE = '';

I’m not sure if this is the best solution,

SET SQL_MODE = ''; INSERT INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

answered Mar 22, 2017 at 17:12

Vinith's user avatar

VinithVinith

1,26614 silver badges25 bronze badges

2

Modify your query and add «IGNORE» as:

INSERT IGNORE INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

answered Feb 15, 2018 at 9:05

Rohit Dhiman's user avatar

3

Its work and tested Copy to Config File: /etc/mysql/my.cnf OR /bin/mysql/my.ini

[mysqld]
port = 3306
sql-mode=""

then restart MySQL

ddb's user avatar

ddb

2,4137 gold badges28 silver badges38 bronze badges

answered Aug 30, 2016 at 7:44

Devraj Gupta's user avatar

0

This appears to be caused by a long-standing (since 2004) bug (#6295) in MySQL, titled

Triggers are not processed for NOT NULL columns.

It was allegedly fixed in version 5.7.1 of MySQL (Changelog, last entry) in 2013, making MySQL behave as “per the SQL standard” (ibid).

answered Apr 24, 2015 at 17:52

B98's user avatar

B98B98

1,22912 silver badges20 bronze badges

3

For Windows WampServer users:

WAMP > MySQL > my.ini

search file for sql-mode=""

Uncomment it.

answered Apr 21, 2017 at 16:23

Andrew's user avatar

AndrewAndrew

17.8k12 gold badges102 silver badges112 bronze badges

1

In Windows Server edit my.ini (for example program filesmysqlmysql server n.nmy.ini)

I would not simply set the sql-mode=»», rather I suggest one removes STRICT_TRANS_TABLES from the line, leave everything as-was, and then restart MySQL from the services utility. Add a comment for future programmers who you are and what you did.

answered Dec 3, 2018 at 18:14

Bill Degnan's user avatar

2

Most of these answers are a lot of work for the not-seasoned coder. Like mentioned the issues is with STRICT_TRANS_TABLES.

First verify STRICT_TRANS_TABLES is running.

$ mysql -u root -p -e "SHOW VARIABLES LIKE 'sql_mode';"

You can disable strict mode on your MySQL server by running the following command on your Linode’s command line:

$ mysql -u root -p -e "SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';"

Then, you can verify that the mode is set by running the following:

$ mysql -u root -p -e "SELECT @@GLOBAL.sql_mode;"

This answer was found here https://www.linode.com/community/questions/17070/how-can-i-disable-mysql-strict-mode

answered Sep 30, 2022 at 21:24

themeowman 's user avatar

i set the fields to not null and problem solved, it updates when an information is commanded to store in it, no more showing msqli message that the field was empty cus you didnt insert value to it, well application of this solution can work on some projects depends on your project structure.

answered Nov 25, 2016 at 1:34

ExploreTech's user avatar

1

This is for SYNOLOGY device users:


  • How to set global variables (strict mode OFF) on SYNOLOGY device.
    (checked on DSM 7.0.1-42218 — device model DS418)

Used PUTTY to connect:
login as root and
sudo su after… (to be admin total)

  • if not exist create my.cnf in:

MariaDB 5:
/var/packages/MariaDB/etc
MariaDB 10:
/var/packages/MariaDB10/etc

  • this should be in the file (at least for strict mode off)
# custom configs
[mysqld]
innodb_strict_mode = OFF
sql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
  • restart mysqld daemon:
    MariaDB 5:
    /usr/syno/bin/synopkg restart MariaDB
    MariaDB 10:
    /usr/syno/bin/synopkg restart MariaDB10

  • check for strict mode enabled at these two global options — both should be not there or off (see config above)

  • log into mysql:
    mysql -u root -p

  • enter password:

show variables like ‘sql_mode’;
show variables like ‘%STRICT%’;


answered Jan 9, 2022 at 6:32

Peter Maly's user avatar

i solved problem changing my.ini file located in data folder. for mysql 5.6 my.ini file moved to data folder rather the bin or mysql installation folder.

answered Jun 2, 2019 at 9:58

sadik keskin's user avatar

I think in name column have null values in this case.

update try set name='abc' where created_by='def';
  

answered Jun 25, 2020 at 5:56

Sasindu's user avatar

I am using Xampp 7.3.28-1 for Linux. It uses MariaDB 10.4.19. Its configuration file is:
/opt/lampp/etc/my.cnf

It does NOT contain an entry that defines sql_mode.
However the query «select @@GLOBAL.sql_mode;» does return a result and it contains the problematic STRICT_TRANS_TABLES. I guess it is by default now.

My solution was to explicitly define the mode by adding this line below [mysqld]:
sql_mode=NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

You can define the modes that you need or just leave it blank.

answered Jun 17, 2021 at 19:05

M.Paunov's user avatar

M.PaunovM.Paunov

1,5971 gold badge13 silver badges19 bronze badges

I found that once I removed what was a doubling up of a foreign key and primary key, when I could have just used the foreign key as the primary key alone in the table. All my code then worked and I was able to upload to db.

answered Nov 21, 2021 at 10:34

Spinstaz's user avatar

SpinstazSpinstaz

2327 silver badges11 bronze badges

My table looks like

create table try ( name varchar(8), CREATED_BY varchar(40) not null);

and then I have a trigger to auto populate the CREATED_BY field

create trigger autoPopulateAtInsert BEFORE INSERT on try for each row set new.CREATED_BY=user();

When I do an insert using

insert into try (name) values ('abc');

the entry is made in the table but I still get the error message

Field 'CREATED_BY' doesn't have a default value Error no 1364

Is there a way to suppress this error without making the field nullable AND without removing the triggfer? Otherwise my hibernate will see these exceptions ( even though the insertions have been made) and then application will crash.

Miklos Aubert's user avatar

asked Mar 15, 2013 at 17:41

kk1957's user avatar

Open phpmyadmin and goto ‘More’ Tab and select ‘Variables’ submenu.
Scroll down to find sql mode.
Edit sql mode and remove ‘STRICT_TRANS_TABLES’
Save it.

answered Oct 19, 2014 at 15:41

Nilesh Dhangare's user avatar

Nilesh DhangareNilesh Dhangare

1,0611 gold badge7 silver badges2 bronze badges

6

In phpmyadmin, perform the following:

select @@GLOBAL.sql_mode

In my case, I get the following:

ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES ,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Copy this result and remove STRICT_TRANS_TABLES. Then perform the following:

set GLOBAL sql_mode='ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

answered Aug 26, 2016 at 7:43

Kamil's user avatar

KamilKamil

8701 gold badge8 silver badges18 bronze badges

5

Set a default value for Created_By (eg: empty VARCHAR) and the trigger will update the value anyways.

create table try ( 
     name varchar(8), 
     CREATED_BY varchar(40) DEFAULT '' not null
);

zardilior's user avatar

zardilior

2,66224 silver badges29 bronze badges

answered Mar 15, 2013 at 17:47

KinSlayerUY's user avatar

KinSlayerUYKinSlayerUY

1,87316 silver badges22 bronze badges

8

When I had this same problem with mysql5.6.20 installed with Homebrew, I solved it by going into my.cnf

nano /usr/local/Cellar/mysql/5.6.20_1/my.cnf

Find the line that looks like so:

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

Comment above line out and restart mysql server

mysql.server restart

Error gone!

answered Sep 15, 2014 at 13:37

Kingsley Ijomah's user avatar

Run mysql console:

mysql -u your_username -p

, select database:

USE your_database;

and run (also from mysql console):

SET GLOBAL sql_mode='';

That will turn off strict mode and mysql won’t complain any more.

To make things clear: your database definition says «this field must have default value defined», and by doing steps from above you say to MySql «neah, just ignore it». So if you just want to do some quick fix locally this solution is ok. But generally you should investigate in your database definition and check if field really needs default value and if so set it. And if default value is not needed this requirement should be removed to have clean situation.

answered Aug 17, 2018 at 8:22

MilanG's user avatar

MilanGMilanG

6,9162 gold badges35 silver badges64 bronze badges

8

As others said, this is caused by the STRICT_TRANS_TABLES SQL mode.

To check whether STRICT_TRANS_TABLES mode is enabled:

SHOW VARIABLES LIKE 'sql_mode';

To disable strict mode:

SET GLOBAL sql_mode='';

answered Aug 24, 2018 at 12:35

Damjan Pavlica's user avatar

Damjan PavlicaDamjan Pavlica

29.6k8 gold badges69 silver badges76 bronze badges

3

Before every insert action I added below line and solved my issue,

SET SQL_MODE = '';

I’m not sure if this is the best solution,

SET SQL_MODE = ''; INSERT INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

answered Mar 22, 2017 at 17:12

Vinith's user avatar

VinithVinith

1,26614 silver badges25 bronze badges

2

Modify your query and add «IGNORE» as:

INSERT IGNORE INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

answered Feb 15, 2018 at 9:05

Rohit Dhiman's user avatar

3

Its work and tested Copy to Config File: /etc/mysql/my.cnf OR /bin/mysql/my.ini

[mysqld]
port = 3306
sql-mode=""

then restart MySQL

ddb's user avatar

ddb

2,4137 gold badges28 silver badges38 bronze badges

answered Aug 30, 2016 at 7:44

Devraj Gupta's user avatar

0

This appears to be caused by a long-standing (since 2004) bug (#6295) in MySQL, titled

Triggers are not processed for NOT NULL columns.

It was allegedly fixed in version 5.7.1 of MySQL (Changelog, last entry) in 2013, making MySQL behave as “per the SQL standard” (ibid).

answered Apr 24, 2015 at 17:52

B98's user avatar

B98B98

1,22912 silver badges20 bronze badges

3

For Windows WampServer users:

WAMP > MySQL > my.ini

search file for sql-mode=""

Uncomment it.

answered Apr 21, 2017 at 16:23

Andrew's user avatar

AndrewAndrew

17.8k12 gold badges102 silver badges112 bronze badges

1

In Windows Server edit my.ini (for example program filesmysqlmysql server n.nmy.ini)

I would not simply set the sql-mode=»», rather I suggest one removes STRICT_TRANS_TABLES from the line, leave everything as-was, and then restart MySQL from the services utility. Add a comment for future programmers who you are and what you did.

answered Dec 3, 2018 at 18:14

Bill Degnan's user avatar

2

Most of these answers are a lot of work for the not-seasoned coder. Like mentioned the issues is with STRICT_TRANS_TABLES.

First verify STRICT_TRANS_TABLES is running.

$ mysql -u root -p -e "SHOW VARIABLES LIKE 'sql_mode';"

You can disable strict mode on your MySQL server by running the following command on your Linode’s command line:

$ mysql -u root -p -e "SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';"

Then, you can verify that the mode is set by running the following:

$ mysql -u root -p -e "SELECT @@GLOBAL.sql_mode;"

This answer was found here https://www.linode.com/community/questions/17070/how-can-i-disable-mysql-strict-mode

answered Sep 30, 2022 at 21:24

themeowman 's user avatar

i set the fields to not null and problem solved, it updates when an information is commanded to store in it, no more showing msqli message that the field was empty cus you didnt insert value to it, well application of this solution can work on some projects depends on your project structure.

answered Nov 25, 2016 at 1:34

ExploreTech's user avatar

1

This is for SYNOLOGY device users:


  • How to set global variables (strict mode OFF) on SYNOLOGY device.
    (checked on DSM 7.0.1-42218 — device model DS418)

Used PUTTY to connect:
login as root and
sudo su after… (to be admin total)

  • if not exist create my.cnf in:

MariaDB 5:
/var/packages/MariaDB/etc
MariaDB 10:
/var/packages/MariaDB10/etc

  • this should be in the file (at least for strict mode off)
# custom configs
[mysqld]
innodb_strict_mode = OFF
sql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
  • restart mysqld daemon:
    MariaDB 5:
    /usr/syno/bin/synopkg restart MariaDB
    MariaDB 10:
    /usr/syno/bin/synopkg restart MariaDB10

  • check for strict mode enabled at these two global options — both should be not there or off (see config above)

  • log into mysql:
    mysql -u root -p

  • enter password:

show variables like ‘sql_mode’;
show variables like ‘%STRICT%’;


answered Jan 9, 2022 at 6:32

Peter Maly's user avatar

i solved problem changing my.ini file located in data folder. for mysql 5.6 my.ini file moved to data folder rather the bin or mysql installation folder.

answered Jun 2, 2019 at 9:58

sadik keskin's user avatar

I think in name column have null values in this case.

update try set name='abc' where created_by='def';
  

answered Jun 25, 2020 at 5:56

Sasindu's user avatar

I am using Xampp 7.3.28-1 for Linux. It uses MariaDB 10.4.19. Its configuration file is:
/opt/lampp/etc/my.cnf

It does NOT contain an entry that defines sql_mode.
However the query «select @@GLOBAL.sql_mode;» does return a result and it contains the problematic STRICT_TRANS_TABLES. I guess it is by default now.

My solution was to explicitly define the mode by adding this line below [mysqld]:
sql_mode=NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

You can define the modes that you need or just leave it blank.

answered Jun 17, 2021 at 19:05

M.Paunov's user avatar

M.PaunovM.Paunov

1,5971 gold badge13 silver badges19 bronze badges

I found that once I removed what was a doubling up of a foreign key and primary key, when I could have just used the foreign key as the primary key alone in the table. All my code then worked and I was able to upload to db.

answered Nov 21, 2021 at 10:34

Spinstaz's user avatar

SpinstazSpinstaz

2327 silver badges11 bronze badges

Общая ошибка 1364 в основном возникает, когда вы пытаетесь вставить / обновить запись в вашей базе данных, где поле, а именно то, которое вызывает исключение, не может быть нулевым, однако вы пытаетесь установить его значение как нулевое (вы не предоставляя значение для этого). Обычно это исключение срабатывает только при использовании MySQL в строгом режиме, Вы можете получить режим, который использует ваш сервер MySQL, с помощью следующего запроса:

SELECT @@sql_mode;

Если вы столкнулись с этим исключением, возможно, потому что у вас включен строгий режим (STRICT_TRANS_TABLES). В этой статье мы расскажем вам о двух способах предотвращения появления этого исключения.

А. Логическое решение

Чтобы предотвратить это исключение, просто предоставьте значение для поля, которое вызывает исключение, или определите, что поле может быть пустым, поэтому при попытке вставить запись значение будет нулевым, но ошибка не будет выдана, для Например, со столбцом, который не может быть пустым, следующий запрос выдаст исключение:

INSERT INTO user (column_a, column_b) VALUES ("Value First Column", NULL);

Таким образом, вы можете изменить столбец, чтобы сделать его обнуляемым:

ALTER TABLE YourTable MODIFY column_b VARCHAR(255) DEFAULT NULL;

И это все, исключение больше не должно появляться.

Б. Серверное решение

Если вы не можете самостоятельно определить значение столбца, потому что вы используете платформу или другой тип логики, которая сначала вставляет запись с нулевым значением, а затем обновляется, вы можете положиться на простой способ, который удаляет строгий режим MySQL. Это в некоторой степени не рекомендуется, так как это предотвращает, например, вставку пустого значения в столбец, который не может быть пустым, вызывая упомянутое исключение. Все происходит в основном как мера контроля, которая предотвращает сбой вашей логики и предотвращает написание нестабильного кода, где вы можете упустить неправильную написанную логику и т. Д.

В других случаях написанная вами логика работает в вашей локальной среде, потому что, вероятно, вы не установили там строгий режим, но на вашем рабочем сервере он не работает из-за этого режима. В этом случае вы можете отключить строгий режим, изменив конфигурационный файл MySQL (my.ini в Windows или my.cnf в Linux) установка sql_mode в пустую строку или удаление STRICT_TRANS_TABLES опция, которая устанавливает MySQL в строгом режиме и имеет NO_ENGINE_SUBSTITUTION режим включен:

[mysqld]
sql-mode=""
# Or
# sql-mode="NO_ENGINE_SUBSTITUTION"

Сохраните изменения, перезапустите службу mysql, и ошибка больше не будет появляться, вместо этого для столбца будет установлено значение null, хотя это не разрешено.

neoan

It’s all about the money

Saving $s has become a hard fact for many individuals and companies these days. In this process I started questioning whether I really need an AWS RDS database instance of whether I run my mysql installation on my EC2. After a rather simple switch, I set up a cron-job for dumps and planned on storing them in a separate S3 bucket (you never know, right?).

The complete process took me less than two hours and I started to rethink some DevOps concepts after being very happy with the benchmarks & performance of my brave EC2 micro instance.

Failing inserts

However, something was off. Did people stop using the POC installation of blua.blue? Since I am a big proponent of privacy, monitoring is limited to a minimum. But API traffic seemed normal.

I tried logging in, changing settings, signing up, commenting, viewing — all seemed working. Until I failed to create a new article.

Unusual debugging

I was unable to reproduce the error locally and none of the error logs on my server showed anything. Hm, how was my error reporting set up again? Sometimes the bold methods are the right choice: I logged every SQL-transaction result and found the following error-number on some transactions: 1364

Field doesn’t have a default value

A quick google search revealed that apparently some of my tables contain columns requiring a value. But didn’t I use exactly the same schemata as previously used via RDS? Thankfully, I am not the first one running into this issue and it seemed I should check somewhere else then I expected: in my MySQL configuration. The fist thing I did was verifying that what I read online is indeed my problem:

mysql> SHOW VARIABLES LIKE 'sql_mode';

Enter fullscreen mode

Exit fullscreen mode

And sure enough, there it was: STRICT_TRANS_TABLES

What this variable does is setting the your MySQL to reject any empty (or most likely undefined) field or your query unless there is a defined default value.
I don’t know about you, but I always lived quite happily with the fact that nullable fields will default to null. And minimizing constraints is definitely a plus on top of the laziness.
So how can I get rid of that behavior?

Changing the configuration

The easiest way is to override your mysql configuration. Depending on your setup, your will find various .cnf files that will offer possibilities. If you are not sure, simply create a new one in the conf-directory (likely /etc/mysql/conf.d/).

Here are the steps to take:

  1. copy your existing mode-variable (see above SQL-query)
  2. define your new sql_mode variable (under mysqld block)
  3. restart the mysql service

If you created your own .cnf-file (e.g. custom.cnf ), it could now look like this:

[mysqld]
sql_mode=IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Enter fullscreen mode

Exit fullscreen mode

After restarting your service, you might want to check your setup again

$ sudo service mysql restart

$ mysql -u root -p
mysql> SHOW VARIABLES LIKE 'sql_mode';

Read next


howtouselinux profile image

Linux Challenge: Introduction to the Linux Command Line

howtouselinux — Nov 8 ’22


muhammadazfaraslam profile image

How to configure React JS app on WSL2 Windows 10

Muhammad Azfar Aslam — Oct 18 ’22


archerallstars profile image

Take your sudo back from Bug 1205094, openSUSE Tumbleweed

Archer Allstars — Nov 6 ’22


edapess profile image

My Arch linux desktop configuration

edapess — Nov 5 ’22

Once unpublished, all posts by sroehrl will become hidden and only accessible to themselves.

If sroehrl is not suspended, they can still re-publish their posts from their dashboard.

Note:

Once unpublished, this post will become invisible to the public and only accessible to neoan.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community 👩‍💻👨‍💻 safe. Here is what you can do to flag sroehrl:

Make all posts by sroehrl less visible

sroehrl consistently posts content that violates DEV Community 👩‍💻👨‍💻’s
code of conduct because it is harassing, offensive or spammy.

Понравилась статья? Поделить с друзьями:
  • Ошибка 1363 калина
  • Ошибка 13611 опель зафира б z18xer
  • Ошибка 13604 на opel astra h
  • Ошибка 13601 опель зафира б
  • Ошибка 136 рено логан