Mysql error unknown variable sql mode

Решил залить проект на свежий ubuntu 16.04 с MySQL 5.7.12 и нашел грабли. Проект не работает с параметром ONLY_FULL_GROUP_BY , который включен по умолчанию. Отключаю лишний параметр так. 1. Смотрю, с какими настройками бежит MySQL: mysql> select @@s...

Решил залить проект на свежий ubuntu 16.04 с MySQL 5.7.12 и нашел грабли. Проект не работает с параметром ONLY_FULL_GROUP_BY, который включен по умолчанию.

Отключаю лишний параметр так.

1. Смотрю, с какими настройками бежит MySQL:

mysql> select @@sql_mode;
+-------------------------------------------------------------------------------------------------------------------------------------------+
| @@sql_mode                                                                                                                                |
+-------------------------------------------------------------------------------------------------------------------------------------------+
| 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 |
+-------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

2. Оставляю все, кроме лишнего:

SET sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
SET global sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
SET session sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
exit

Но все это работает до перезагрузки сервера. Как добавить это в конфигурацию MySQL сервера?

http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html — читатал, не помогло. По оффициальной документации: «To set the SQL mode at server startup, use the … sql-mode="modes" in an option file such as my.cnf …»

В ubuntu 16.04 несколько мест, где лежат конфигурации mysql. В /etc/mysql/my.cnf ярлык на /etc/alternatives/my.cnf в нем:

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

В /etc/mysql/conf.d/ есть mysql.cnf c:

[mysql]

Пробовал в файл /etc/mysql/conf.d/mysql.cnf добавлять вниз это:

sql-mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

или это:

sql-mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";

Перезапускал сервис и получал соответственно:

# mysql -u root -p
mysql: [ERROR] unknown variable 'sql-mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

# mysql -u root -p
mysql: [ERROR] unknown variable 'sql-mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";'

Operating System               : Ubuntu Linux Xenial Xerus (16.04)

Database                             : MySQL 5.7.12

Problem :

In the middle of restoring a MySQL dump script file for WordPress web-based site, suddenly the process stop. Below is the error which is displayed in the middle of database restore process :

username@hostname:~# mysql -uroot -p wordpress_dbname < /location_path_of_mysql/mysql_dump_file_name.sql
mysql: [ERROR] unknown variable 'sql_mode=NO_ZERO_DATE'
username@hostname:~#

After searching on google for solving the solution above, there are several steps that has been tried and executed as shown below :

One of the main problem is because variable the mode NO_ZERO_DATE which is seems needed in order for the MySQL dump file properly executed is already deprecated. Based on MySQL Reference Manual it is said that :

The NO_ZERO_DATE mode affects whether the server permits ‘0000-00-00’ as a valid date. It effect also depends on whether strict SQL mode is enabled.

The other explanation is shown below :

As of MySQL 5.6.17, NO_ZERO_DATE is deprecated and setting the sql_mode  value to include it generates a warning.

It can be viewed in the following URL : https://dev.mysql.com/doc/refman/5.6/en/sql-mode.html. Below is the snapshot of the information :

no-zero-date-deprecated

NO_ZERO_DATE sql_mode is deprecated since MySQL 5.6.17. It is a mode concerning datetime type

The thing is, the version of MySQL used is above MySQL 5.6.17 which is definitely NO_ZERO_DATE sql_mode is already deprecated.

To find out the version of currently used MySQL, we can execute the following command :

mysql --version

The execution of the above command is shown below :

username@hostname:~$ mysql --version
mysql  Ver 14.14 Distrib 5.7.12, for Linux (x86_64) using  EditLine wrapper
username@hostname:~$

Another way to find out the currently used MySQL version is by logging in to MySQL command console as shown below :

username@hostname:~# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 5
Server version: 5.7.12-0ubuntu1.1 (Ubuntu)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
mysql>

In the above output display, it is said that Server version : 5.7.12.

Solution               :

1. Try to fix the sql_mode by doing the following thing :

Set the sql_mode value from MySQL command console.
Try to login first to MySQL command console by typing the following command :

mysql -uroot –p

The execution of the command is shown below :

username@hostname:~# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 5
Server version: 5.7.12-0ubuntu1.1 (Ubuntu)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
mysql>

2. Get the sql_mode first by executing the following command :

mysql>show variables like 'sql_mode';
+---------------+-------------------------------------------------------------------------------------------------------------------------------------------+
| Variable_name | Value                                                                                                                                     
|+---------------+-------------------------------------------------------------------------------------------------------------------------------------------+
| sql_mode      | 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 |
+---------------+-------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0,02 sec)

3. Set the appropriate mode to successfully restore database :

Try to remove the sql_mode contains NO_ZERO_DATE and also NO_ZERO_IN_DATE which is probably related by executing the following command in MySQL command console :

mysql>set sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
Query OK, 0 rows affected, 1 warning (0,00 sec)
mysql> quit;

4. Reexecute the restore process :

username@hostname:~# mysql -uroot -p wordpress_dbname < /location_path_of_mysql/mysql_dump_file_name.sql Enter password: ERROR 1067 (42000) at line 285: Invalid default value for 'comment_date' username@hostname:~#

The error has changed and the problem is still exist. The restore database process has failed.

Solution :

After looking at the dump database script file at line 285 which seems to be the culprit of the problem, it has been decided to fully disable any sql_mode which has already been set.

Below is the line which caused the problem :

  `comment_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',

It is still relates on the problem of datetime which is needed to set the default value of date combined with time. Below is the step which is taken to solve the problem :

1. Directly edit MySQL configuration file as shown below :

In Ubuntu Linux 16.04, the configuration file exist in the following directory :

/etc/mysql/mysql.conf.d/mysqld.cnf

2. Add the following line to the [mysqld] block as follows :

[mysqld]
user                                       = mysql
pid-file                                   = /var/run/mysqld/mysqld.pid
socket                                     =  /var/run/mysqld/mysqld.sock
port                                       = 3306
basedir                                    = /usr
datadir                                    = /var/lib/mysql
tmpdir                                     = /tmp
lc-messages-dir                            = /usr/share/mysql

The line which is added after the ‘lc-messages-dir’ concerning the sql_mode is shown below :

sql_mode                            =

3. Just empty the value and depends on your setting, from my point of view as long as it is placed in the [mysqld] block configuration, it will have impact.

4. Restart the MySQL service as shown below :

username@hostname:~# service mysql restart
username@hostname:~#

5. After restarting MySQL service, directly restore the database by executing the comand as follows :

username@hostname:~# mysql -uroot -p wordpress_dbname < /location_path_of_mysql/mysql_dump_file_name.sql
Enter password:Enter password:
You have new mail in /var/mail/root
username@hostname:~#

As shown in the above output, the process has already success.

For a quick recap, this is the following things that I have done to solve the above problem :

  1. Set sql_mode through MySQL Command Console which is not fully succeed.
  2. Edit MySQL database server configuration and add the following line under [mysqld] block configuration section :
sql_mode =

Depends on the operating system, the locationof MySQL database server configuration will also vary.

  1. Restart MySQL service database.
  2. Try to re-execute the restore process of MySQL dump file.

3 ответы

sql-mode должно быть в [mysqld] раздел, а не в [mysql] раздел; если ты двигаешься sql-mode=ANSI до [mysqld] раздел, он должен работать.

Создан 10 сен.

Я почти уверен, что причина, по которой он не работает, заключается в том, что это аргумент для mysqld, а не для клиента. Я придумал альтернативный способ сделать это вместо этого. Отредактируйте своих пользователей my.cnf i.e. ~/.my.cnf быть примерно таким:

[client]
init-command="set sql_mode='TRADITIONAL'"

ответ дан 10 мая ’13, 05:05

ответ дан 10 мая ’13, 05:05

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

mysql

or задайте свой вопрос.

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

1 2009-03-18 11:26:48

  • kurtq
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-03-18
  • Сообщений: 2

Тема: Помогите. Ошибка mySQL 1064,1193

Пробую загрузити бази на хост. Викинуло слідуючу помилку:
SQL-запрос:

— phpMyAdmin SQL Dump
— version 2.11.3
— http://www.phpmyadmin.net

— Host: localhost
— Generation Time: Jan 23, 2008 at 12:58 AM
— Server version: 5.0.51
— PHP Version: 5.2.5
SET SQL_MODE = «NO_AUTO_VALUE_ON_ZERO»;

Ответ MySQL: 
#1193 — Unknown system variable ‘SQL_MODE’

Я трошки полазив по формах, прочитав, шо можна замінити— на #. Зробив це, різниці ніякої.
Тоді  я прописав # напроти SET SQL_MODE = «NO_AUTO_VALUE_ON_ZERO» і вийшло шось типу :
SQL-запрос:

# phpMyAdmin SQL Dump
# version 2.11.3
# http://www.phpmyadmin.net
#
# Host: localhost
# Generation Time: Jan 23, 2008 at 12:58 AM
# Server version: 5.0.51
# PHP Version: 5.2.5
# SET SQL_MODE=»NO_AUTO_VALUE_ON_ZERO»;
#
# Database: `pro`
#
# ———————————————————
#
# Table structure for table `tb_ads`
#
CREATE TABLE `tb_ads` (
`id` int( 11 ) NOT NULL AUTO_INCREMENT ,
`user` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`ip` varchar( 15 ) COLLATE cp1251_general_ci NOT NULL ,
`tipo` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`visitime` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`ident` int( 11 ) DEFAULT NULL ,
`fechainicia` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`paypalname` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`paypalemail` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`plan` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`bold` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`highlight` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`url` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`description` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`category` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL ,
`members` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL default ‘0’,
`outside` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL default ‘0’,
`total` varchar( 150 ) COLLATE cp1251_general_ci NOT NULL default ‘0’,
KEY `id` ( `id` )
) ENGINE = MYISAM DEFAULT CHARSET = cp1251 COLLATE = cp1251_general_ci AUTO_INCREMENT =29;

Ответ MySQL: 
#1064 — You have an error in your SQL syntax.  Check the manual that corresponds to your MySQL server version for the right syntax to use near ‘collate cp1251_general_ci NOT NULL,
  `ip` varchar(15) collate
Шо не робив, нічого не виходить. Поможіть, хто може, бо я вже зовсім вимотався…

2 Ответ от Hanut 2009-03-18 15:50:13

  • Hanut
  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,723

Re: Помогите. Ошибка mySQL 1064,1193

kurtq
Вероятно вы импортируете дамп на сервер, где стоит старая версия MySQL. Вам необходимо уточнить версию MySQL и создать дамп в соответствии с ней. На странице экспорта есть выпадающий список «Режим совместимости», где он и задается.

В следующий раз отвечу по-латышски.

3 Ответ от kurtq 2009-03-18 17:01:05

  • kurtq
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-03-18
  • Сообщений: 2

Re: Помогите. Ошибка mySQL 1064,1193

Версия сервера: 4.0.27
Версия MySQL-клиента: 4.0.27
Использованы расширения PHP: mysql
А як переробити дамп під старий MySQL? Є якісь проги-редактори? Скиньте будь-ласка якусь силочку на них. Буду дуже вдячний!!!

4 Ответ от Hanut 2009-03-18 18:03:24

  • Hanut
  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,723

Re: Помогите. Ошибка mySQL 1064,1193

kurtq
При создании дампа, на странице экспорта в phpMyAdmin выберите режим совместимости MYSQL40.

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

Понравилась статья? Поделить с друзьями:
  • Mysql error safe update mode
  • Mysql error number 1267
  • Mysql error number 1130
  • Mysql error number 1114
  • Mysql error number 1062