Sql error 1064 sqlstate 42000

I'm using latest version of MySQL ==> mysql-5.6.10-winx64.zip Created the database and every thing is ok 'I think' when I try to execute this simple command; "select * from family" I got this er...

I’m using latest version of MySQL ==> mysql-5.6.10-winx64.zip

Created the database and every thing is ok ‘I think’
when I try to execute this simple command;

"select * from family"

I got this error :

Error code 1064, SQL state 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 ‘OPTION SQL_SELECT_LIMIT=DEFAULT’ at
line 1

I’ve spent much time searching for a solution but no solution was found :(

Álvaro González's user avatar

asked Feb 27, 2013 at 13:48

Hazem Taha's user avatar

7

That looks like an error coming from a JDBC driver. When the JDBC driver initializes the connection, it sends several commands to the MySQL server, one of which is:

SET OPTION SQL_SELECT_LIMIT=DEFAULT

The problem is that the SET OPTION syntax has been deprecated for some time and is now no longer valid in MySQL 5.6. Here’s a relevant bug conversation from MySQL’s bug database:

Bug #66659: mysql 5.6.6m9 fails on OPTION SQL_SELECT_LIMIT=DEFAULT

Try upgrading your JDBC MySQL driver. The bug conversation lists some other options in case upgrading the driver is not an option.

answered Feb 28, 2013 at 4:45

hrunting's user avatar

hruntinghrunting

3,81727 silver badges23 bronze badges

I followed the instructions above and this worked for me!

  1. Download latest jar file from here:
    http://dev.mysql.com/downloads/mirror.php?id=412737
    Unzip it
    Copy jar file «mysql-connector-java-5.1.25-bin.jar»
    to this folder: C:Program FilesNetBeans 7.3idemodulesext

  2. In Netbeans IDE: Disconnect from database.
    Click Services. Expand Drivers. Right-click on MySQL and press Customize.
    Add latest driver
    Remove previous driver.

  3. Re-connect to dabatase within IDE.

answered May 8, 2013 at 13:43

Fresh's user avatar

FreshFresh

1111 silver badge2 bronze badges

1

I had the same problem few weeks back. Followed the following steps and it very much resolved the issue.

  1. Copied the latest version (mysql-connector-java-5.1.23-bin) of the jar file to ..NetBeans 7.3idemodulesext. My earlier version of the driver was mysql-connector-java-5.1.18-bin.

  2. Change the driver version within NetBeans IDE. In the IDE’s Services window, expand Drivers -> right-click on MySQL (Connector/J driver) and select Customize. Remove the earlier driver and point it to the latest one (C:Program Files (x86)NetBeans 7.3idemodulesextmysql-connector-java-5.1.23-bin.jar). Click ok and restart IDE.

This should resolve the problem.

answered Apr 4, 2013 at 16:36

farmbytes's user avatar

1

If the driver suggestion does not work, check your sql for unprintable characters. I just spent an hour troubleshooting this issue only to discover a hidden u+200b character at the end of my sql statement.

answered Oct 29, 2014 at 23:24

Brice's user avatar

BriceBrice

3463 silver badges14 bronze badges

0

I got the same Error when i was dumping mysql table structure file in to DB. Mistake was putting the Syntax for dropping all table before but not checking their existence in the Database.
Issue was at » DROP TABLE usermgmt«.
I removed that code of lines of dropping tables and it proceeded with out any error this time.

answered Jan 7, 2016 at 6:42

D8Sasi's user avatar

1

I prefixed the name of the table with the database name such as

select * from database_name.table_name;

and it worked perfectly, so most likely there’s a name conflict.

answered May 2, 2017 at 11:31

rachid el kedmiri's user avatar

I’m using latest version of MySQL ==> mysql-5.6.10-winx64.zip

Created the database and every thing is ok ‘I think’
when I try to execute this simple command;

"select * from family"

I got this error :

Error code 1064, SQL state 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 ‘OPTION SQL_SELECT_LIMIT=DEFAULT’ at
line 1

I’ve spent much time searching for a solution but no solution was found :(

Álvaro González's user avatar

asked Feb 27, 2013 at 13:48

Hazem Taha's user avatar

7

That looks like an error coming from a JDBC driver. When the JDBC driver initializes the connection, it sends several commands to the MySQL server, one of which is:

SET OPTION SQL_SELECT_LIMIT=DEFAULT

The problem is that the SET OPTION syntax has been deprecated for some time and is now no longer valid in MySQL 5.6. Here’s a relevant bug conversation from MySQL’s bug database:

Bug #66659: mysql 5.6.6m9 fails on OPTION SQL_SELECT_LIMIT=DEFAULT

Try upgrading your JDBC MySQL driver. The bug conversation lists some other options in case upgrading the driver is not an option.

answered Feb 28, 2013 at 4:45

hrunting's user avatar

hruntinghrunting

3,81727 silver badges23 bronze badges

I followed the instructions above and this worked for me!

  1. Download latest jar file from here:
    http://dev.mysql.com/downloads/mirror.php?id=412737
    Unzip it
    Copy jar file «mysql-connector-java-5.1.25-bin.jar»
    to this folder: C:Program FilesNetBeans 7.3idemodulesext

  2. In Netbeans IDE: Disconnect from database.
    Click Services. Expand Drivers. Right-click on MySQL and press Customize.
    Add latest driver
    Remove previous driver.

  3. Re-connect to dabatase within IDE.

answered May 8, 2013 at 13:43

Fresh's user avatar

FreshFresh

1111 silver badge2 bronze badges

1

I had the same problem few weeks back. Followed the following steps and it very much resolved the issue.

  1. Copied the latest version (mysql-connector-java-5.1.23-bin) of the jar file to ..NetBeans 7.3idemodulesext. My earlier version of the driver was mysql-connector-java-5.1.18-bin.

  2. Change the driver version within NetBeans IDE. In the IDE’s Services window, expand Drivers -> right-click on MySQL (Connector/J driver) and select Customize. Remove the earlier driver and point it to the latest one (C:Program Files (x86)NetBeans 7.3idemodulesextmysql-connector-java-5.1.23-bin.jar). Click ok and restart IDE.

This should resolve the problem.

answered Apr 4, 2013 at 16:36

farmbytes's user avatar

1

If the driver suggestion does not work, check your sql for unprintable characters. I just spent an hour troubleshooting this issue only to discover a hidden u+200b character at the end of my sql statement.

answered Oct 29, 2014 at 23:24

Brice's user avatar

BriceBrice

3463 silver badges14 bronze badges

0

I got the same Error when i was dumping mysql table structure file in to DB. Mistake was putting the Syntax for dropping all table before but not checking their existence in the Database.
Issue was at » DROP TABLE usermgmt«.
I removed that code of lines of dropping tables and it proceeded with out any error this time.

answered Jan 7, 2016 at 6:42

D8Sasi's user avatar

1

I prefixed the name of the table with the database name such as

select * from database_name.table_name;

and it worked perfectly, so most likely there’s a name conflict.

answered May 2, 2017 at 11:31

rachid el kedmiri's user avatar

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.

So, you’re creating a custom SQL query to perform a task in the database. After putting the code together and running it in PHPmyAdmin it responds with a 1064 error. It may look similar to this:

1064 error message

The 1064 error displays any time you have an issue with your SQL syntax, and is often due to using reserved words, missing data in the database, or mistyped/obsolete commands. So follow along and learn more about what the 1064 error is, some likely causes, and general troubleshooting steps.

Note: Since syntax errors can be hard to locate in long queries, the following online tools can often save time by checking your code and locating issues:

  • PiliApp MySQL Syntax Check
  • EverSQL SQL Query Syntax Check & Validator

Causes for the 1064 error

  • Reserved Words
  • Missing Data
  • Mistyped Commands
  • Obsolete Commands

This may seem cryptic since it is a general error pointing to a syntax issue in the SQL Query statement. Since the 1064 error can have multiple causes, we will go over the most common things that will result in this error and show you how to fix them. Follow along so you can get your SQL queries updated and running successfully.

Using Reserved Words

Every version of MySQL has its own list of reserved words. These are words that are used for specific purposes or to perform specific functions within the MySQL engine. If you attempt to use one of these reserved words, you will receive the 1064 error. For example, below is a short SQL query that uses a reserved word as a table name.

CREATE TABLE alter (first_day DATE, last_day DATE);

How to fix it:

Just because the word alter is reserved does not mean it cannot be used, it just has special requirements to use it as the MySQL engine is trying to call the functionality for the alter command. To fix the issue, you will want to surround the word with backticks, this is usually the button just to the left of the “1” button on the keyboard. The code block below shows how the code will need to look in order to run properly.

CREATE TABLE `alter` (first_day DATE, last_day DATE);

Missing Data

Sometimes data can be missing from the database. This causes issues when the data is required for a query to complete. For example, if a database is built requiring an ID number for every student, it is reasonable to assume a query will be built to pull a student record by that ID number. Such a query would look like this:

SELECT * from students WHERE studentID = $id

If the $id is never properly filled in the code, the query would look like this to the server:

SELECT * from students WHERE studentID =

Since there is nothing there, the MySQL engine gets confused and complains via a 1064 error.

How to fix it:

Hopefully, your application will have some sort of interface that will allow you to bring up the particular record and add the missing data. This is tricky because if the missing data is the unique identifier, it will likely need that information to bring it up, thus resulting in the same error. You can also go into the database (typically within phpMyAdmin) where you can select the particular row from the appropriate table and manually add the data.

Mistyping of Commands

One of the most common causes for the 1064 error is when a SQL statement uses a mistyped command. This is very easy to do and is easily missed when troubleshooting at first. Our example shows an UPDATE command that is accidentally misspelled.

UDPATE table1 SET id = 0;

How to fix it:

Be sure to check your commands prior to running them and ensure they are all spelled correctly.

Below is the syntax for the correct query statement.

UPDATE table1 SET id = 0;

Obsolete Commands

Some commands that were deprecated (slated for removal but still allowed for a period of time) eventually go obsolete. This means that the command is no longer valid in the SQL statement. One of the more common commands is the ‘TYPE‘ command. This has been deprecated since MySQL 4.1 but was finally removed as of version 5.1, where it now gives a syntax error. The ‘TYPE‘ command has been replaced with the ‘ENGINE‘ command. Below is an example of the old version:

CREATE TABLE t (i INT) TYPE = INNODB;

This should be replaced with the new command as below:

CREATE TABLE t (i INT) ENGINE = INNODB;

For developers or sysadmins experienced with the command line, get High-Availability and Root Access for your application, service, and websites with Cloud VPS Hosting.

Error 1064 Summary

As you can see there is more than one cause for the 1064 error within MySQL code. Now, you know how to correct the issues with your SQL Syntax, so your query can run successfully. This list will be updated as more specific instances are reported.

Дата: 25.11.2013

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

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

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

SELECT mid, time, title, artist, download, view_count, rating, vote_num FROM dle_mservice WHERE category = ‘1’ AND approve = ‘1’ ORDER BY time DESC LIMIT -10,10;
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 ‘-10,10’ at line 1

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

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

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

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

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

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

  • В MySQL допускается использование ключевых слов в качестве имен столбцов/таблиц, но при этом их необходимо заключать в обратные кавычки (там где буква ё на клавиатуре).
    Пример:

    select order from test;
    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 ‘order from test’ at line 1
    MariaDB [test]> select `order` from test;
    +——-+
    | order |
    +——-+
    |  NULL |
    +——-+

  • По умолчанию ; разделяет команды. Если же нужно выполнить набор из нескольких инструкций как одну команду (например, при создании процедур, фунуций, триггеров), то в зависимости от используемого клиента может потребоваться переопределить разделитель с помощью DELIMITER, иначе интерпретация команды остановится на первой ; и будет ошибка синтаксиса. Пример:

    delimiter //
    create procedure test()
    begin
    set @a=1;
    select @a;
    end//

    Обратите внимание: DELIMITER это команда консольного клиента mysql, необходимость его использования зависит от того как вы передаете команду серверу. Например,:

    • mysql_query() выполняет содержимое как одну команду, добавление delimiter приведет к error 1064 с цитатой, начинающейся со слова delimiter
    • phpmyadmin удаляет слово delimiter из-за чего возникает error 1064 с цитатой, начинающейся с переопределенного разделителя
    • в MysqlQueryBrowser напротив необходимо использовать delimiter.

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

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

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

    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 ‘TYPE=MyISAM CHARACTER SET `utf8`’ at line 29

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

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

    #1064 — You have an error in your SQL syntax near ‘DEFAULT CHARACTER SET cp1251 COLLATE cp1251_general_ci’ at line 1

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

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

    #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 ‘
    CREATE TABLE `jos_banner` (
      `bid` int(11) NOT NULL auto_increment,
      `ci‘ at line 1

    Значит ваш дамп содержит 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.

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

$db->query («SELECT id, title, date, category, alt_name, flag FROM « . PREFIX . «_post WHERE MATCH (title, short_story, full_story, xfields, title) AGAINST (‘$body’) AND id != «.$row[‘id’].» AND approve=’1′».$where_date.» LIMIT «.$config[‘related_number’]);

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

P.S. Если после прочтения статьи ваш вопрос с MySQL Error 1064 остался нерешенным, то задавайте его на форуме SQLinfo

Дата публикации: 25.11.2013

© Все права на данную статью принадлежат порталу SQLInfo.ru. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

На связке Node.js + Express + MySQL при деплое на сервер возникает ошибка в одном из маршрутов.
Если обратиться к этому маршруту то получаем ошибку

"code":"ER_PARSE_ERROR",
"errno":1064,
"sqlMessage":"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 'CREATE OR REPLACE VIEW tmp AS SELECT                    TEACH.name,             ' at line 1",
"sqlState":"42000",
"index":0

но если взять код запроса из сообщения с ошибкой и вставить в Workbench то он прекрасно отработает.
Собственно сам текст запроса, в который динамически прилетают даты и ИД города. Форматирование а-ля
Workbench.

CREATE OR REPLACE VIEW tmp AS
    SELECT 
        TEACH.name,
        CAT.description,
        WRK.idTEACHER,
        LEC.idLECTURE,
        LEC.out,
        COUNT(TGFL.idTRAININGFL) AS people,
        WRK.hours
    FROM
        LECTURE LEC
            INNER JOIN
        TRAININGFL TGFL ON TGFL.idLECTURE = LEC.idLECTURE
            AND TGFL.idCITY = 1
            AND TGFL.date_attestation BETWEEN '2018-01-01' AND '2018-01-28'
            INNER JOIN
        WORKLOAD WRK ON WRK.idLECTURE = TGFL.idLECTURE
            INNER JOIN
        TEACHER TEACH ON TEACH.idTEACHER = WRK.idTEACHER
            INNER JOIN
        CAT_TEACHER CAT ON CAT.idCAT_TEACHER = TEACH.idCAT
    GROUP BY LEC.idLECTURE , WRK.idTEACHER;CREATE OR REPLACE VIEW allpeople AS
    SELECT 
        COUNT(TGFL.idTRAININGFL) AS allpeople
    FROM
        TRAININGFL TGFL
    WHERE
        idCITY = 1
            AND TGFL.date_attestation BETWEEN '2018-01-01' AND '2018-01-28';SELECT 
    name,
    IFNULL(allin, 0) AS allin,
    IFNULL(hoursin, 0) AS hoursin,
    IFNULL(allout, 0) AS allout,
    IFNULL(hoursout, 0) AS hoursout,
    IFNULL(t1.people1, 0) AS people1in,
    IFNULL(t2.people1, 0) AS people1out,
    IFNULL(t1.people2, 0) AS people2in,
    IFNULL(t2.people2, 0) AS people2out,
    IFNULL(t1.people3, 0) AS people3in,
    IFNULL(t2.people3, 0) AS people3out,
    IFNULL(t1.people4, 0) AS people4in,
    IFNULL(t2.people4, 0) AS people4out,
    allpeople.allpeople
FROM
    tmp
        LEFT JOIN
    (SELECT 
        idTEACHER,
            SUM(IF(tmp.hours = 1, people, 0)) AS people1,
            SUM(IF(tmp.hours = 2, people, 0)) AS people2,
            SUM(IF(tmp.hours = 3, people, 0)) AS people3,
            SUM(IF(tmp.hours = 4, people, 0)) AS people4,
            COUNT(idLECTURE) AS allin,
            SUM(IF(tmp.hours > 0, hours, 0)) AS hoursin
    FROM
        tmp
    WHERE
        1 = 1 AND tmp.out = 1
    GROUP BY hours , idTEACHER
    ORDER BY name) AS t1 ON tmp.idTEACHER = t1.idTEACHER
        LEFT JOIN
    (SELECT 
        idTEACHER,
            SUM(IF(tmp.hours = 1, people, 0)) AS people1,
            SUM(IF(tmp.hours = 2, people, 0)) AS people2,
            SUM(IF(tmp.hours = 3, people, 0)) AS people3,
            SUM(IF(tmp.hours = 4, people, 0)) AS people4,
            COUNT(idLECTURE) AS allout,
            SUM(IF(tmp.hours > 0, hours, 0)) AS hoursout
    FROM
        tmp
    WHERE
        1 = 1 AND tmp.out = 0
    GROUP BY hours , idTEACHER
    ORDER BY name) AS t2 ON tmp.idTEACHER = t2.idTEACHER
        LEFT JOIN
    allpeople ON 1 = 1
GROUP BY tmp.idTEACHER
ORDER BY description , name

На Windows где собственно и пишу код с теми же самыми версиями пакетов все работает без геморроя.
Где то магия, где пока понять не могу :(

Понравилась статья? Поделить с друзьями:
  • Sql error 1062 sqlstate 23000
  • Sql error 25006 error cannot execute update in a read only transaction
  • Sql error code 242
  • Spring kafka error handler
  • Sql error 1062 23000 duplicate entry 1 for key users primary