Mysql 42000 ошибка

The MySQL Error code 1064 SQL State 42000 occurs mainly due to the SQL syntax error or due to the outdated JDBC MySQL driver.

Oops!! Stuck with MySQL Error code 1064 SQL State 42000? We can help you in fixing it.

The SQL State Error 42000 occurs mainly due to the SQL syntax error or due to the outdated JDBC MySQL driver.

At Bobcares, we often get requests to fix MySQL errors, as a part of our Server Management Services.

Today, let’s see how our Support Engineers fix MySQL errors for our customers.

Why MySQL Error code 1064 SQL State 42000 occurs?

The MySQL Error code mainly occurs due to the SQL Syntax error. It happens when MySQL is unable to validate the commands.

The Syntax Error occurs due to many factors like mistyping the commands, deprecated or missing data from the database.

In some cases, the error occurs when the JDBC driver initializes the connection.

MySQL Error code 1064 SQL State 42000

How we fix the MySQL Error code 1064?

Recently, one of our customers approached us saying that he is getting MySQL Error code 1064 SQL State 42000. On checking, we found an error in the SQL syntax.

Now, let’s see the main causes for this Error 1064 SQL State 42000 and how our Support Engineers fix them.

1. Using Reserved Words

The reserved words perform some specific functions within the MySQL engine.

Sometimes we receive the error while using the reserved words,  The error occurs when the MySQL is not meeting the exact requirements for using the particular keyword.

Create Table alter (first name, last name);

The alter is a reserved word. To fix the error 1064 with the reserved word we specify the alter word within backticks.

Create Table 'alter' (first name, last name);

2. Outdated JDBC driver

When the JDBC driver initializes the connection, it sends several commands to the MySQL server. At that time we may receive the MySQL Error code SQL State 42000.

The problem is that the commands were deprecated for some time which results in the error.

We fix the error by upgrading the JDBC MySQL driver to the latest version.

3. Mistyping and Missing of Data

The 1064 error occurs when the data is not found in the database or mistyping the commands.

In case, if the data is missing from the database, we manually add the data to the database. Also, we make sure that all the commands are spelled correctly.

[Need any assistance with SQL State 42000 Error codes? – We’ll help you]

Conclusion

In short, today we discussed in detail on MySQL Error code 1064 and saw how our Support Engineers find the fix for this 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.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Sqlstate 42000 Is a general code that come together with other number. Most often comes with the code 1064 and is related with SQL syntax error. This kind of error has been seen reported mostly on MySQL but also on other type of databases. This happen because your command is not a valid one within the “Structured Query Language” or SQL. Syntax errors are just like grammar errors in linguistics. In the following article we will try to explain the MySQL error 1064 but not only. Also we will show other error codes that comes together with Sqlstate[42000].

Full view of my sql error code 1064:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL (or any other like MariaDb) server version for the right syntax to use near (And here is the part of the code where the error comes)

sqlstate 42000 - mysql error 1064 – you have an error in your sql syntax

sqlstate 42000 – mysql error 1064 – you have an error in your sql syntax

Other error codes related with Sqlstate 42000:

  • 1 – syntax error or access violation 1055
  • 2 – syntax error or access violation 1071 specified key was too long
  • 3 – syntax error or access violation 1066 not unique table/alias
  • 4 – syntax error or access violation 1068 multiple primary key defined

Understand and FIX MySQL error 1064 – sqlstate 42000

SQL 1064 means that MySQL can’t understand your command!

This type of error first need to be understood and after that you can fix it. The common causes of this error are:

  • Upgrading MySQL or any other database to another version
  • Using Wrong syntax that is not supported on your current version
  • Error in applying the back tick symbol or while creating a database without them can also create an error
  • Due to using reserved words
  • Particular data missing while executing a query
  • Mistyped/obsolete commands

If you see words like “near” or “at line”, you need to check for problems in those lines of the code before the command ends.

How do I Fix SQL Error Code 1064?

  1. Read the message on the error:

So in general the error tells you where the parser encountered the syntax error. MySQL also suggest how to fix it.  Check the example below …..

  1. Check the text of your command!

In some cases the PHP commands has wrong lines. Create SQL commands using programing language can be the good example of this. So you will need to check and fix those commands. Use echo, console.log(), or its equivalent to show the entire command so you can see it.

  1. Mistyping of commands

The error can occur also when you misspell a command (e.g. instead of UPDATE you write UDPATE). This can occur often since are so easy to miss. To prevent this, make sure that you review your command for any typing error before running it. There are a lot of online syntax checkers that can help to debug your queries.

  1. Check for reserved words

Reserved words are words that vary from one MySQL version to another. Every version has its list of keywords that are reserved. They are used to perform specific functions in the MySQL engine. If you read the error and identified that occurred on an object identifier, check that it isn’t a reserved word (and, if it is, be sure that it’s properly quoted). “If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.”  You can find a full list of the reserved words specific for each MySQL version and their usage requirements at MySQL.com.

  1. Obsolete commands – another reason

Another possible reason for the sqlstate 42000 MySQL error 1064 is when you use outdated commands. As Platforms grow and change, some commands that were useful in the past are replaced by more efficient ones. A number of commands and keywords have been deprecated. This mean that they are due for removal, but still allowed for a short period of time before they turn obsolete. On cases that you have an older backup of a MySQL database that you want to import, a quick solution is to just search and replace “TYPE=InnoDB” with “ENGINE=InnoDB”.

  1. Particular data is missing while executing a query

If the relevant data missing from the database which is required for the query, you’re obviously going to run into problems.  Using phpMyAdmin or MySQL Workbench you can enter the missing data. Interface of the application allow you to add the missing data manually to an appropriate row of the table.

You have an error in your sql syntax

You have an error in your sql syntax

“You have an error in your sql syntax” – Example 1

The error code generated jointly with the statement “syntax error or access violation”, “You have an error in your SQL syntax; check the manual that corresponds to your MySQL (or any other like MariaDB) server version for the right syntax to use near” and after that the part of SQL code where the issue is. So in simple way, the error view is showing you also where is the error. For example we have the error:

“Check the manual that corresponds to your MySQL server version for the right syntax to use near 'from, to, name, subject, message) VALUES ('[email protected]', '[email protected],com' at line 1”

So how to understand this?

from is a keyword in SQL. You may not use it as a column name without quoting it. In MySQL, things like column names are quoted using back ticks, i.e. `from`. Or you can just rename the column.

Another example of “You have an error in your sql syntax” sqlstate 42000 – Example 2

Error:

check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 [ SELECT COUNT(*) as count,region, MONTHNAME(date) asmonth FROM tempur_stores.stats WHERE date > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) AND date < DATE(NOW()) GROUP BY region, MONTH(date ]

On the query:

$stmt = DB::query(Database::SELECT, 'SELECT COUNT(*) as `count`,`region`, MONTHNAME(`date`) as`month` FROM tempur_stores.stats WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) AND `date` < DATE(NOW()) GROUP BY `region`, MONTH(`date`');

The above query is missing a closing parenthesis in the query:

$stmt = DB::query(Database::SELECT, 'SELECT COUNT(*) as `count`,`region`, MONTHNAME(`date`) as`month`

FROM tempur_stores.stats

WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK)

AND `date` < DATE(NOW())

GROUP BY `region`, MONTH(`date`');

----------  ^ right there

Just put a parenthesis ) before that apostrophe and it should work.

MariaDB error 1064 – Example 3

An example with MariaDB version issue. Trying to do example of tagging and when:

$id = Questions::create([            'body' => request('title'),            'skillset_id' => request('skillsetId'),            'tags' => ['red', 'blue']        ])->id;

Getting error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘>’$.”en”‘ = ? and `type` is null limit 1’ at line 1 (SQL: select * from `tags` where `name`->’$.”en”‘ = red and `type` is null limit 1)

Reason is that is using MariaDB and JSON columns are only supported by MySQL. Convert to MySQL to resolve the issue.

MariaDB error 1064

MariaDB error 1064

Fix error 1064 mysql 42000 while creating a database – Example 4

MySQL error 1064 can be appearing also while you are creating database using hyphen in the name like Test-Db. This can be solved by using back tick around the database name properly or remove the hyphen in the database name.

Example:

mysql> create database Test-DB;

You will get error:

ERROR 1064 (42000): 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 '-DB' at line 1

Solution:

mysql> create database ` Test-DB `;

So adding back tick around the database name will solve the issue.

Transfer WordPress MySQL database to another server

Exporting WordPress database to another server can also be cause the 1064 error. Can be resolved by choosing the compatibility mode and changing the database version to the current version you’re using. Please select the compatibility mode under the advanced tab when performing a backup and after that click the auto-detect file character set when restoring the MySQL database.

Read Also

  1. Location of SQL Server Error Log File
  2. How to fix SQL Server Error 18456
  3. How to Restore Master Database

Conclusions:

The reason behind the error it’s related closely to the end of error message. We would need to see the SQL query to understand completely the issue you’re facing. So this is the reason that we can’t completely fix the MySQL error 1064 but we exposed some examples for you. You will need to review the documentation for the version of MySQL that you are having this error appear with and your syntax to fix the problem. There are multiple reasons for its cause. We suggest you perform the sqlstate 42000 error fixes if only has experience on MySQL database.

#1 22.11.2010 05:31:00

NewUse
Участник
Зарегистрирован: 22.11.2010
Сообщений: 9

ERROR 1064 (42000) Я Полный чайник

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

DROP DATABASE myfirstdb IF EXISTS;

ERROR 1064 (42000): 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 ‘IF EXISTS’ at line 1

Стоит MySQL 5.1
Импортирую схему именно для MySQL, правда, для какой версии — точно не знаю sad

Подскажите, где ошибка в синтаксисе, и как он должен выглядеть, либо киньте ссылку, на поддерживаемые функции данной версии и их описание, пожалуйста smile

Спасибо.


Комментарий модератора.
В статье ERROR 1064 (42000) объясняется, что означает ошибка сервера MySQL №1064, рассматриваются типичные ситуации и причины возникновения этой ошибки, а также даются рекомендации по исправлению.

Отредактированно NewUse (22.11.2010 05:31:34)

Неактивен

#2 22.11.2010 06:42:48

vasya
Архат
MySQL Authorized Developer
Откуда: Орел
Зарегистрирован: 07.03.2007
Сообщений: 5791

Re: ERROR 1064 (42000) Я Полный чайник

Неактивен

#3 23.11.2010 01:50:30

NewUse
Участник
Зарегистрирован: 22.11.2010
Сообщений: 9

Re: ERROR 1064 (42000) Я Полный чайник

Да, спасибо, заработало, помогите, пожалуйста исправить ещё одну ошибочку такого же типа (несовместимость версий):
Сайтик под  предположительно php4+MySQL — версия ранняя 2004г или ранее:

while ($row = $query->fetchRow()) {
    unset($ROW);
    $row[packet] = «<A HREF=packet.php?gid=$row[gid]>$row[packet]n«;
    $TMP_ROW = «<A HREF=edit_packet.php?gid=$row[gid]><img src=images/edit.gif alt=««.$INDEX_PAGE[edit].«« border=0></A>n«;
    if ($row[action] > 0){
            $TMP_ROW.=» | <A HREF=edit_price.php?gid=$row[gid]><img src=images/price.gif alt=««.$INDEX_PAGE[price].«« border=0></A>n«;
    }
    $TMP_ROW.=» | <A HREF=del_packet.php?gid=$row[gid]><img src=images/delete.gif alt=««.$NIBS_TEXT[delete].«« border=0></A>n«;
    $row[action] = $TMP_ROW;
    $count = $db->getRow(«select count($username) as $username from users where gid=$row[gid]»);
    $row[num_users] = $count[$username];
    $TOTAL_USER += $count[$username];
    $TRAF_ARRAY = $db->GetRow(«select sum(in_bytes) as in_bytes, sum(out_bytes) as out_bytes from «.NIBS_ACCT_TABLE.» where gid=».$row[gid]);
    $row[gid] = round($TRAF_ARRAY[in_bytes]/(1024*1024),$ROUND_DIGIT).«/»;
    $row[gid].= round($TRAF_ARRAY[out_bytes]/(1024*1024),$ROUND_DIGIT);
    $TOTAL_IN  += $TRAF_ARRAY[in_bytes];
    $TOTAL_OUT += $TRAF_ARRAY[out_bytes];
    while(list($key,$val)=each($row)){
        if ($HEADER){
            $TMP_HEADER[] = array(VARS   => $NIBS_TEXT[$key],
                                  TD_CLR => HDR_CLR,
                                  TH     => true);
        }
        $ROW[] = array(VARS   => $val,
                       TD_PAR => «align=middle»,
                       TD_CLR => DEF_CLR);
    }
    if($HEADER){
        $HEADER  = false;
        $ARRAY[] = $TMP_HEADER;
    }
    $ARRAY[]=$ROW;

}

в логах ошибка:

PHP Fatal error:  Call to a member function fetchRow() on a non-object in /usr/local/www/data/index.php on line 13

Неактивен

#4 23.11.2010 01:59:31

paulus
Администратор
MySQL Authorized Developer and DBA
Зарегистрирован: 22.01.2007
Сообщений: 6740

Re: ERROR 1064 (42000) Я Полный чайник

Как следует из текста ошибки — Вы пытаетесь вызвать метод у сущности,
не являющейся объектом. Задавайте, пожалуйста, вопросы по PHP на
webew.ru.

Неактивен

#5 23.11.2010 15:28:00

NewUse
Участник
Зарегистрирован: 22.11.2010
Сообщений: 9

Re: ERROR 1064 (42000) Я Полный чайник

Спасибо, а такой синтаксис в MySQL5 допустим?

SELECT packet, num as num_users,gid,tos as action FROM packets order by num

Неактивен

#6 23.11.2010 16:17:12

paulus
Администратор
MySQL Authorized Developer and DBA
Зарегистрирован: 22.01.2007
Сообщений: 6740

Re: ERROR 1064 (42000) Я Полный чайник

Да.

Неактивен

#7 24.11.2010 17:01:53

NewUse
Участник
Зарегистрирован: 22.11.2010
Сообщений: 9

Re: ERROR 1064 (42000) Я Полный чайник

Не подскажите, ещё один тупой вопрос от полного чайника?:
почему (и в каких случаях) в MySQL 5 на запрос:

SELECT packet, num as num_users,gid,tos as action FROM packets order by num
 

Может вернуться ошибка, или тип, не соответствующий стандартному?
В результате к ответу при попытки применить функцию:

function FetchRow()
    {
        if ($this->EOF) {
            $false = false;
            return $false;
        }
        $arr = $this->fields;
        $this->_currentRow++;
        if (!$this->_fetch()) $this->EOF = true;
        return $arr;
    }
   

Вываливается ошибка

PHP Fatal error:  Call to a member function fetchRow() on a non-object in /usr/local/www/data/index.php on line 13
 

Я правда чайник, но с помощью выше рекомендованного сайта определил, что ошибка именно в результате запроса MySQL.

Неактивен

#8 24.11.2010 17:37:09

paulus
Администратор
MySQL Authorized Developer and DBA
Зарегистрирован: 22.01.2007
Сообщений: 6740

Re: ERROR 1064 (42000) Я Полный чайник

Не-а, ошибка в сценарии PHP, который не проверяет, что вернулся объект,
а просто дергает его метод. Ищите название объекта на 13 строке, а потом
смотрите, где он определяется. Ошибка где-то там.

Неактивен

#9 24.11.2010 17:56:57

NewUse
Участник
Зарегистрирован: 22.11.2010
Сообщений: 9

Re: ERROR 1064 (42000) Я Полный чайник

так ошибка то и возникает из-за невернго формата возврата запроса  из БД:

Ошибка возникает в:

query($sql)

где

$sql=«SELECT packet, num as num_users,gid,tos as action FROM packets order by num»

при попытки применить к нему функцию FetchRow (описание выше) в php это выглядит так:

$query->fetchRow()

Вот от сюда и вопрос, в каких случаях БД может выдавать разный ответ (вернее разный формат ответа),  сейчас проверил вручную:
вот ответ:

ERROR 1054 (42S22): Unknown column ‘num’ in ‘field list’

Отредактированно NewUse (24.11.2010 18:13:33)

Неактивен

#10 24.11.2010 18:17:37

paulus
Администратор
MySQL Authorized Developer and DBA
Зарегистрирован: 22.01.2007
Сообщений: 6740

Re: ERROR 1064 (42000) Я Полный чайник

Ура. Нет такого столбца. Наконец-то Вы добрались до проблемы smile

ALTER TABLE packets ADD num INT;

Неактивен

#11 24.11.2010 18:41:19

NewUse
Участник
Зарегистрирован: 22.11.2010
Сообщений: 9

Re: ERROR 1064 (42000) Я Полный чайник

Угу, походу схема БД была не верной, ща переправлю и инструкташку под фриНИБС с Веб-мордой накатаю, там уже пришлось кое-что поменять smile

СПАСИБО!!!!!

Подскажите, пожалуйста, как подредактировать схему, чтоб этой ошибки не возникало:

DROP TABLE IF EXISTS packets;
CREATE TABLE `packets` (
  `gid` bigint(15) unsigned NOT NULL auto_increment,
  `packet` varchar(128) NOT NULL default »,    
  `deposit` double(16,6) NOT NULL default ‘0.000000’,
  `credit` double(16,6) NOT NULL default ‘0.000000’,
  `tos` tinyint(1) unsigned NOT NULL default ‘0’,
  `do_with_tos` tinyint(1) unsigned NOT NULL default ‘1’,
  `direction` tinyint(1) unsigned NOT NULL default ‘0’,    
  `fixed` tinyint(1) unsigned NOT NULL default ‘0’,    
  `fixed_cost` double(16,6) NOT NULL default ‘0.000000’,
  `activated` tinyint(1) unsigned NOT NULL default ‘1’,    
  `activation_time` int(10) NOT NULL default ‘2678400’,    
  `blocked` tinyint(1) unsigned NOT NULL default ‘0’,    
  `total_time_limit` bigint(15) unsigned NOT NULL default ‘0’,
  `month_time_limit` bigint(15) unsigned NOT NULL default ‘0’,
  `week_time_limit` bigint(15) unsigned NOT NULL default ‘0’,
  `day_time_limit` bigint(15) unsigned NOT NULL default ‘0’,
  `total_traffic_limit` bigint(15) unsigned NOT NULL default ‘0’,
  `month_traffic_limit` bigint(15) unsigned NOT NULL default ‘0’,
  `week_traffic_limit` bigint(15) unsigned NOT NULL default ‘0’,
  `day_traffic_limit` bigint(15) unsigned NOT NULL default ‘0’,    
  `total_money_limit` double(16,6) NOT NULL default ‘0.000000’,    
  `month_money_limit` double(16,6) NOT NULL default ‘0.000000’,    
  `week_money_limit` double(16,6) NOT NULL default ‘0.000000’,    
  `day_money_limit` double(16,6) NOT NULL default ‘0.000000’,    
  `login_time` varchar(254) NOT NULL default »,        
  `huntgroup_name` varchar(64) NOT NULL default »,        
  `simultaneous_use` smallint(3) unsigned NOT NULL default ‘0’,    
  `port_limit` smallint(3) unsigned NOT NULL default ‘0’,    
  `session_timeout` bigint(15) unsigned NOT NULL default ‘0’,    
  `idle_timeout` bigint(15) unsigned NOT NULL default ‘0’,    
  `framed_ip` varchar(16) NOT NULL default »,            
  `framed_mask` varchar(15) NOT NULL default »,        
  `no_pass` tinyint(1) unsigned NOT NULL default ‘0’,        
  `no_acct` tinyint(1) unsigned NOT NULL default ‘0’,        
  `allow_callback` tinyint(1) unsigned NOT NULL default ‘0’,    
  `other_params` MEDIUMTEXT,
  `allowed_servers` varchar(254) NULL,                
  `up` int(5) NULL,                
  `down` int(5) NULL,
  `ippool_name` varchar(64) NULL,
  `provider_id` bigint not null default ‘0’,
  PRIMARY KEY  (`gid`),
  UNIQUE KEY `packet` (`packet`)
);
 

Отредактированно NewUse (24.11.2010 19:54:12)

Неактивен

#12 24.11.2010 20:29:10

paulus
Администратор
MySQL Authorized Developer and DBA
Зарегистрирован: 22.01.2007
Сообщений: 6740

Re: ERROR 1064 (42000) Я Полный чайник

У меня ощущение, что на этот вопрос я уже ответил в предыдущем сообщении sad

Неактивен

#13 24.11.2010 22:07:31

NewUse
Участник
Зарегистрирован: 22.11.2010
Сообщений: 9

Re: ERROR 1064 (42000) Я Полный чайник

Да, я же писал, что чайник, но судя по аналогии должно быть что-то типа:

`num` int
 

?

Не подскажите, кто такое может сообщать

Ошибка изменения пареметров — (uid is empty)

может ли это быть MySQL

Неактивен

#14 24.11.2010 22:17:24

NewUse
Участник
Зарегистрирован: 22.11.2010
Сообщений: 9

Re: ERROR 1064 (42000) Я Полный чайник

а, вот, всё обнаружил запрос:

INSERT INTO users (user,password, gid,deposit,credit,add_date,blocked,activated,crypt_method) values (»,», , , , ‘0000-00-00’, », »,»)

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 ‘ , , ‘0000-00-00′, », »,»)’ at line 1

В чём здесь ошибка? Подскажите, пожалуйста?

Неактивен

#15 25.11.2010 11:08:10

deadka
Администратор
Зарегистрирован: 14.11.2007
Сообщений: 2399

Re: ERROR 1064 (42000) Я Полный чайник

Вы бы привели создание таблицы users ;-), а то трудно анализировать запрос вставки, не зная структуры таблицы. Посмотреть структуру можно запросом «show create table users;».

Ошибка как минимум в том, что Вы указали поля, в которые хотите вставить данные (gid,deposit,credit), но не вставляете туда данных, это недопустимо. Если запрос будет иметь вид

INSERT INTO users (user,password,add_date,blocked,activated,crypt_method) values (»,»,’0000-00-00′,»,»,»)

то у него больше шансов на успех, I guarantee it.

Отредактированно deadka (25.11.2010 11:09:57)


Зеленый свет для слабаков, долги отдают только трусы, тру гики работают только в консоли…

Неактивен

#16 25.11.2010 15:49:58

NewUse
Участник
Зарегистрирован: 22.11.2010
Сообщений: 9

Re: ERROR 1064 (42000) Я Полный чайник

Да, спасибо, дело было в скелете, взял скелет от болеее старой версии и добавил нужные поля, теперь всё ОК smile

Неактивен

If you are working with MySQL 5.7 and you find an exception when storing a lot of fields with text format:

SQLSTATE[42000]: Syntax error or access violation: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED may help. In current row format, BLOB prefix of 768 bytes is stored inline.

And you are sure that the row format of the table is set to Dynamic, you are probably facing an issue with the innodb log file size and the strict mode. In this article, we’ll show you how to prevent this exception from appearing in MySQL 5.7.

1. Find my.cnf file

As first step, you will need to search for the configuration file of MySQL. There is no internal MySQL command to trace the location of this file, so the file might be in 5 (or more) locations, and they would all be valid because they load cascading:

  • /etc/my.cnf
  • /etc/mysql/my.cnf
  • $MYSQL_HOME/my.cnf
  • [datadir]/my.cnf
  • ~/.my.cnf

Those are the default locations MySQL looks at, however if you still don’t find the correct file, you may run the following command on your terminal:

find / -name my.cnf

Once you find the file, open it with a CLI editor like nano and follow the next step.

2. Increase innodb_log_file_size value

In our case, the file is located at /etc/mysql/my.cnf, so we could edit the file with nano using the file with the following command:

nano /etc/mysql/my.cnf

You will need to disable the strict mode of MySQL and increase the size of innodb log file. When innodb_strict_mode is enabled, InnoDB returns errors rather than warnings for certain conditions. Like many database management systems, MySQL uses logs to achieve data durability (when using the default InnoDB storage engine). This ensures that when a transaction is committed, data is not lost in the event of crash or power loss. MySQL’s InnoDB storage engine uses a fixed size (circular) Redo log space. The size is controlled by innodb_log_file_size. If you increase the value of this property, you will get rid off this exception when storing multiple columns of text in MySQL 5.7.

The theme about which size is right for the innodb log file won’t be covered in this article, instead we recommend you to read this article that contains a detailed explanation and facts about how to choose this value. As we are just sharing with you the solution to this problem, we’ll use the value of 512M, so the parameters to add to the mysqld block of the my.cfn file will be:

# Important: inside the mysqld block
[mysqld]
# Add new log file size
innodb_log_file_size=512M
# Disable strict mode
innodb_strict_mode=0

An example of how the file should look like:

#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/
[mysqld]
# Add new log file size
innodb_log_file_size=512M
# Disable strict mode
innodb_strict_mode=0

Although we didn’t cover a detailed explanation of the problem caused by the row size limitation that is removed by the dynamic row format, you may want to inform yourself about this problem visiting this article. After saving changes in the file , restart mysql with the cli depending of your os and installation process e.g:

# Ubuntu
sudo service mysql restart

# CentOS
/etc/init.d/mysqld start

Happy coding !

Содержание

  1. ИТ База знаний
  2. Полезно
  3. Навигация
  4. Серверные решения
  5. Телефония
  6. Корпоративные сети
  7. SQL error 1064 – что делать?
  8. Бесплатный вводный урок на онлайн курс по Linux
  9. Использование зарезервированных слов
  10. Недостающая информация в таблице
  11. Интенсив по Виртуализации VMware vSphere 7
  12. Полезно?
  13. Почему?
  14. MySQL error 1064
  15. 1. Запрос в редакторе.
  16. 2. Перенос базы на другой сервер.
  17. 3. Некорректная работа сайта.

ИТ База знаний

Курс по Asterisk

Полезно

— Узнать IP — адрес компьютера в интернете

— Онлайн генератор устойчивых паролей

— Онлайн калькулятор подсетей

— Калькулятор инсталляции IP — АТС Asterisk

— Руководство администратора FreePBX на русском языке

— Руководство администратора Cisco UCM/CME на русском языке

— Руководство администратора по Linux/Unix

Навигация

Серверные решения

Телефония

FreePBX и Asterisk

Настройка программных телефонов

Корпоративные сети

Протоколы и стандарты

SQL error 1064 – что делать?

Вам когда-нибудь приходилось видеть ошибку 1064 при работе с MySQL? Причем она указывает на некие синтаксические ошибки в SQL запросе, и эти ошибки могут быть совсем неочевидны – подробнее расскажем ниже.

Бесплатный вводный урок на онлайн курс по Linux

Мы собрали концентрат самых востребованных знаний, которые позволят начать карьеру администраторов Linux, расширить текущие знания и сделать уверенный шаг в DevOps

Использование зарезервированных слов

У каждой версии MySQL есть свой список зарезервированных слов – эти слова используются для особых задач или особых функций внутри движка MySQL. При попытке использовать какие-то из них, вы получите ту самую ошибку 1064. К примеру, ниже пример SQL запроса, который использует зарезервированное слово в качестве имени таблицы.

Как этого избежать? Просто! Только потому что слово alter зарезервировано, это не значит, что его нельзя использовать – нужно просто по-особенному приготовить! Чтобы движок MySQL не воспринимал это слово как команду, мы будем просто использовать кавычки и оно взлетит:

Недостающая информация в таблице

Иногда какой-то части информации в таблице нет и это может вызвать эту ошибку, если запрос обращался к этим данным. К примеру, если в таблице был список сотрудников, и каждому был присвоен ID, было бы логично предположить, что запрос будет вызывать запись сотрудника вместе с номером ID, например:

Если пресловутый $id никогда не был правильно указан, запрос будет выглядеть для MySQL сервера следующим образом:

Т.к запрос по сути пустой, движок MySQL будет выдавать ту самую ошибку 1064. Исправляется это следующим образом – вам нужно каким-то образом вызвать конкретную запись и добавить недостающую информацию, причем сделать это не так просто: если пытаться вызвать запись по уникальному номеру, скорее всего вы увидите точно такую ошибку. Можно с помощью phpMyAdmin вручную выбрать необходимую строку и добавить нужную информацию.

Опечатки в командах

Одной из самых частых причин ошибки 1064 являются опечатки. И иногда можно десять раз посмотреть на команду и не увидеть опечатки – как пример ниже с командой UPDATE:

Соответственно, проверяйте команды свежим взглядом и старайтесь не пропускать такого. Правильный вариант будет выглядеть так:

Устаревшие команды

Некоторые команды устарели, и в новых версиях MySQL начинают выдавать хорошо знакомую нам ошибку. К примеру, команда ‘TYPE’ была признана устаревшей в MySQL 4.1 и была полностью удалена в MySQL 5.1, где при попытке использовать ее вы можете видеть ту самую ошибку. Вместо нее необходимо использовать команду ‘ENGINE’.

Ниже неверный вариант:

А вот правильный, модный и современный вариант (как оно должно быть, чтобы не было ошибки):

Заключение

Как можно видеть, для одной несчастной ошибки, указывающей на синтаксис, может быть целый ряд разных причин. Так что когда вы видите подобную ошибку – вспомните эту статью и проверьте все возможные варианты ?

Интенсив по Виртуализации VMware vSphere 7

Самое важное про виртуализацию и VMware vSphere 7 в 2-х часовом онлайн-интенсиве от тренера с 30-летним стажем. Для тех, кто начинает знакомство с виртуализацией и хочет быстро погрузиться в предметную область и решения на базе VMware

Полезно?

Почему?

😪 Мы тщательно прорабатываем каждый фидбек и отвечаем по итогам анализа. Напишите, пожалуйста, как мы сможем улучшить эту статью.

😍 Полезные IT – статьи от экспертов раз в неделю у вас в почте. Укажите свою дату рождения и мы не забудем поздравить вас.

Источник

MySQL error 1064

Автор: Василий Лукьянчиков , vl (at) sqlinfo (dot) ru

Статья ориентирована на новичков. В ней объясняется, что означает ошибка сервера MySQL №1064, рассматриваются типичные ситуации и причины возникновения этой ошибки, а также даются рекомендации по исправлению.

Рассмотрим простейший пример.

Сервер MySQL сообщает, что в первой строке нашего SQL запроса имеется синтаксическая ошибка, и в одинарных кавычках цитирует часть запроса с того места где начинается ошибка. Это очень полезное свойство, так как позволяет сразу определить место, которое сервер счел ошибочным. В данном случае это ‘-10,10’, ошибка возникает из-за того, что параметр LIMIT не может быть отрицательным числом.

Однако, бывает и так, что цитируемый кусок запроса не содержит синтаксической ошибки. Это означает, что данная часть запроса находится не на своем месте из-за чего весь запрос становится синтаксически неверным. Например, отсутствует разделитель между двумя запросами, пропущен кусок запроса, невидимый символ в дампе и т.д. Неудобством таких ситуаций является то, что сообщение об ошибке не содержит исходный запрос. Действия по исправлению зависят от контекста возникновения ошибки. Таковых всего 3:

1. Запрос в редакторе.

Самый простейший случай — вы пишите свой запрос в редакторе. Если причина не опечатка, то:

    Смотреть в документации синтаксис команды для вашей версии сервера MySQL.

Обратите внимание: речь идет о версии сервера MySQL, а не клиента (phpmyadmin, workbench и т.д.). Версию сервера можно узнать выполнив команду select version ( ) ;

2. Перенос базы на другой сервер.

У вас есть дамп (т.е. файл с расширением .sql) и при попытке его импортировать вы получаете ошибку 1064. Причины:

В различных версиях набор ключевых слов и синтаксис может немного отличаться. Наиболее распространенный случай: команда create table, в которой ключевое слово type было заменено на engine. Например, если вы получаете ошибку:

Это означает, что вы переносите базу в пятую версию сервера MySQL, в котором ключевое слово TYPE не поддерживается и его нужно заменить на ENGINE.

Редко бываю случаи, когда перенос идет на старый (

3.23) сервер, который кодировки не поддерживает. Тогда ошибка будет иметь вид:

Такое может произойти, если вы переносите базу с хостинга на локальный комп, где стоит древняя версия MySQL. Лучшим решением в данном случае будет не править дамп, а обновить MySQL.

Часто проблемы вызваны тем, что дамп делается неродными средствами MySQL (например, phpmyadmin) из-за чего в нем могут быть BOM-маркер, собственный синтаксис комментариев, завершения команды и т.д. Кроме того при использовании того же phpmyadmin возможна ситуация при которой из-за ограничения апача на размер передаваемого файла команда будет обрезана, что приведет к ошибке 1064. Например, если вы получаете ошибку:

Значит ваш дамп содержит BOM-маркер. Это три байта в начале файла, помогающие программе определить что данный файл сохранен в кодировке UTF-8. Проблема в том, что MySQL пытается интерпретировать их как команду из-за чего возникает ошибка синтаксиса. Нужно открыть дамп в текстовом редакторе (например, Notepad++) и сохранить без BOM.

Для избежания подобных проблем при создании дампа и его импорте лучше пользоваться родными средствами MySQL, см http://sqlinfo.ru/forum/viewtopic.php?id=583

3. Некорректная работа сайта.

Если во время работы сайта появляются ошибки синтаксиса, то, как правило, причина в установке вами сомнительных модулей к вашей cms. Лучшее решение — отказаться от их использования. Еще лучше предварительно проверять их работу на резервной копии.

Пример. Движок dle 7.2, поставили модуль ,вроде бы все Ок, но:

MySQL Error!
————————
The Error returned was:
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 ‘AND approve=’ 1 ‘ AND date 2008 -10 -04 04 : 34 : 25 ‘ LIMIT 5’ at line 1

Error Number:
1064
SELECT id, title, date , category, alt_name, flag FROM dle_post WHERE MATCH ( title, short_story, full_story, xfields, title ) AGAINST ( ‘Приобретение и оплата скрипта ‘ ) AND id != AND approve= ‘1’ AND date ‘2008-10-04 04:34:25’ LIMIT 5

В данном примере мы видим, что причина ошибки в отсутствии значения после «id != «

Обратите внимание: из процитированного сервером MySQL куска запроса причина ошибки не ясна. Если ваша CMS не показывает весь запрос целиком, то нужно в скриптах найти место где выполняется данный запрос и вывести его на экран командой echo.

Кусок кода, который отвечает за данный запрос это

Далее можно искать откуда взялась переменная $row и почему в ней нет элемента ‘id’ и вносить исправления, но лучше отказаться от использования такого модуля (неизвестно сколько сюрпризов он еще принесет).

Источник

Понравилась статья? Поделить с друзьями:
  • Mysql 2014 error
  • Mysql 1366 ошибка
  • Myrtille error 1001
  • Mypy ignore error
  • Myphoneexplorer obex errorcode d0 internal server error