Как ошибку db error syntax error

When issuing a command to MySQL, I’m getting error #1064 «syntax error».

  1. What does it mean?

  2. How can I fix it?

asked May 7, 2014 at 10:32

eggyal's user avatar

TL;DR

Error #1064 means that MySQL can’t understand your command. To fix it:

  • Read the error message. It tells you exactly where in your command MySQL got confused.

  • Examine your command. If you use a programming language to create your command, use echo, console.log(), or its equivalent to show the entire command so you can see it.

  • Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.

  • Check for reserved words. If the error occurred on an object identifier, check that it isn’t a reserved word (and, if it is, ensure that it’s properly quoted).

  1. Aaaagh!! What does #1064 mean?

    Error messages may look like gobbledygook, but they’re (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.

    As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.

    • What is this «syntax» of which you speak? Is it witchcraft?

      Whilst «syntax» is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.

      For example, the following English sentence contains a syntax error (because the indefinite article «a» must always precede a noun):

      This sentence contains syntax error a.

    • What does that have to do with MySQL?

      Whenever one issues a command to a computer, one of the very first things that it must do is «parse» that command in order to make sense of it. A «syntax error» means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.

      It’s important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.

  2. How do I fix it?

    Obviously, one needs to determine how it is that the command violates MySQL’s grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…

    • Read the message!

      MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:

      UPDATE my_table WHERE id=101 SET name='foo'
      

      That command yields the following error message:

      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 'WHERE id=101 SET name='foo'' at line 1

      MySQL is telling us that everything seemed fine up to the word WHERE, but then a problem was encountered. In other words, it wasn’t expecting to encounter WHERE at that point.

      Messages that say ...near '' at line... simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.

    • Examine the actual text of your command!

      Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:

      $result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
      

      If you write this this in two lines

      $query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
      $result = $mysqli->query($query);
      

      then you can add echo $query; or var_dump($query) to see that the query actually says

      UPDATE userSET name='foo' WHERE id=101
      

      Often you’ll see your error immediately and be able to fix it.

    • Obey orders!

      MySQL is also recommending that we «check the manual that corresponds to our MySQL version for the right syntax to use«. Let’s do that.

      I’m using MySQL v5.6, so I’ll turn to that version’s manual entry for an UPDATE command. The very first thing on the page is the command’s grammar (this is true for every command):

      UPDATE [LOW_PRIORITY] [IGNORE] table_reference
          SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
          [WHERE where_condition]
          [ORDER BY ...]
          [LIMIT row_count]
      

      The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it’s enough to recognise that: clauses contained within square brackets [ and ] are optional; vertical bars | indicate alternatives; and ellipses ... denote either an omission for brevity, or that the preceding clause may be repeated.

      We already know that the parser believed everything in our command was okay prior to the WHERE keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference must be followed by the SET keyword: whereas in our command it was actually followed by the WHERE keyword. This explains why the parser reports that a problem was encountered at that point.

    A note of reservation

    Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual’s description of what was expected at that point), virtually every syntax error can be readily identified.

    I say «virtually all», because there’s a small class of problems that aren’t quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:

    UPDATE my_table SET where='foo'
    

    Again, the parser does not expect to encounter WHERE at this point and so will raise a similar syntax error—but you hadn’t intended for that where to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:

    If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.

    [ deletia ]

    The identifier quote character is the backtick (“`”):

    mysql> SELECT * FROM `select` WHERE `select`.id > 100;

    If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:

    mysql> CREATE TABLE "test" (col INT);
    ERROR 1064: You have an error in your SQL syntax...
    mysql> SET sql_mode='ANSI_QUOTES';
    mysql> CREATE TABLE "test" (col INT);
    Query OK, 0 rows affected (0.00 sec)

3

It is late but will help others and ofcourse will save time :)
My query was working in MySQL 5.7 in local system but on live we have version MySQL 8 and query stop working.

Query:

SELECT t.*
FROM groups t
ORDER BY t.id DESC
LIMIT 10 OFFSET 0

Output in MySQL 8:

Error in query (1064): Syntax error near ‘groups t ORDER BY t.id DESC’
at line …

I came to know groups is reserved word so I have to wrap groups with « quotes or change the table name to solve this issue.

answered Jul 18, 2021 at 13:13

Muhammad Shahzad's user avatar

Muhammad ShahzadMuhammad Shahzad

9,23021 gold badges84 silver badges130 bronze badges

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can’t figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

answered Apr 19, 2017 at 10:54

Umair Malhi's user avatar

Umair MalhiUmair Malhi

5551 gold badge4 silver badges16 bronze badges

3

Ahhh….that’s a bit more helpful.. :)

> node ./src/server.js; webpack-dev-server --inline --hot --progress --port 4200; tsc ./src/server.ts --watch

executing query: SELECT * FROM information_schema.tables WHERE table_catalog = 'TEST_DB' AND table_schema = 'public'
executing query: SELECT * FROM information_schema.columns WHERE table_catalog = 'TEST_DB' AND table_schema = 'public'
executing query: SELECT t.relname AS table_name, i.relname AS index_name, a.attname AS column_name 
                                FROM pg_class t, pg_class i, pg_index ix, pg_attribute a
                                WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid
                                AND a.attnum = ANY(ix.indkey) AND t.relkind = 'r' AND t.relname IN ()
                                ORDER BY t.relname, i.relname
executing query: SELECT table_name, constraint_name FROM information_schema.table_constraints WHERE table_catalog = 'TEST_DB' AND constraint_type = 'FOREIGN KEY'
executing query: SELECT * FROM information_schema.table_constraints WHERE table_catalog = 'TEST_DB' AND constraint_type = 'UNIQUE'
executing query: SELECT table_name, constraint_name FROM information_schema.table_constraints WHERE table_catalog = 'TEST_DB' AND constraint_type = 'PRIMARY KEY'
query failed: SELECT t.relname AS table_name, i.relname AS index_name, a.attname AS column_name 
                                FROM pg_class t, pg_class i, pg_index ix, pg_attribute a
                                WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid
                                AND a.attnum = ANY(ix.indkey) AND t.relkind = 'r' AND t.relname IN ()
                                ORDER BY t.relname, i.relname
Error during connection to the db:  { error: syntax error at or near ")"
    at Connection.parseE (/Users/jordan/Documents/workspace/tester/node_modules/pg/lib/connection.js:554:11)
    at Connection.parseMessage (/Users/jordan/Documents/workspace/tester/node_modules/pg/lib/connection.js:381:17)
    at Socket.<anonymous> (/Users/jordan/Documents/workspace/tester/node_modules/pg/lib/connection.js:117:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:543:20)
  name: 'error',
  length: 84,
  severity: 'ERROR',
  code: '42601',
  detail: undefined,
  hint: undefined,
  position: '380',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'scan.l',
  line: '1081',
  routine: 'scanner_yyerror' }


Syntax errors are quite common while coding.

But, things go for a toss when it results in website errors.

PostgreSQL error 42601 also occurs due to syntax errors in the database queries.

At Bobcares, we often get requests from PostgreSQL users to fix errors as part of our Server Management Services.

Today, let’s check PostgreSQL error in detail and see how our Support Engineers fix it for the customers.

What causes error 42601 in PostgreSQL?

PostgreSQL is an advanced database engine. It is popular for its extensive features and ability to handle complex database situations.

Applications like Instagram, Facebook, Apple, etc rely on the PostgreSQL database.

But what causes error 42601?

PostgreSQL error codes consist of five characters. The first two characters denote the class of errors. And the remaining three characters indicate a specific condition within that class.

Here, 42 in 42601 represent the class “Syntax Error or Access Rule Violation“.

In short, this error mainly occurs due to the syntax errors in the queries executed. A typical error shows up as:

Here, the syntax error has occurred in position 119 near the value “parents” in the query.

How we fix the error?

Now let’s see how our PostgreSQL engineers resolve this error efficiently.

Recently, one of our customers contacted us with this error. He tried to execute the following code,

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
WITH m_ty_person AS (return query execute sql)
select name, count(*) from m_ty_person where name like '%a%' group by name
union
select name, count(*) from m_ty_person where gender = 1 group by name;
END
$$ LANGUAGE plpgsql;

But, this ended up in PostgreSQL error 42601. And he got the following error message,

ERROR: syntax error at or near "return"
LINE 5: WITH m_ty_person AS (return query execute sql)

Our PostgreSQL Engineers checked the issue and found out the syntax error. The statement in Line 5 was a mix of plain and dynamic SQL. In general, the PostgreSQL query should be either fully dynamic or plain. Therefore, we changed the code as,

RETURN QUERY EXECUTE '
WITH m_ty_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM m_ty_person WHERE name LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM m_ty_person WHERE gender = 1 GROUP BY name$x$;

This resolved the error 42601, and the code worked fine.

[Need more assistance to solve PostgreSQL error 42601?- We’ll help you.]

Conclusion

In short, PostgreSQL error 42601 occurs due to the syntax errors in the code. Today, in this write-up, we have discussed how our Support Engineers fixed this error for our customers.

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»;

Introduction

Actually, this article has a relation with the existence of the previous article. That previous article exist in this link with the title of ‘How to Solve Error Message Model Attribute Problem SyntaxError: invalid syntax in Django Application’. It is actually just inappropriate format of the column name available in the SQL file. That SQL file actually containing an INSERT statement for restoring data to the targeted database. But since there is a column name which is not following the standard rule which starts with a character that is not number or letter, it cause the restore process to fail.

The following is just to describe that accessing the database is not the cause of the problem.

Microsoft Windows [Version 10.0.19042.1288]
(c) Microsoft Corporation. All rights reserved.

C:UsersPersonal>cd 

C:>psql -Upostgres -d db_app
Password for user postgres:
psql (14.0)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.

db_app=# q

After that, the process for inserting records by importing it or restoring it using the following command exist as follows :

C:>psql -Uuser_app -d db_app < "C:UsersPersonalDownloadsinsert-current-product.sql"
Password for user db_user:
ERROR: syntax error at or near "["
LINE 1: ...,[product_code...
^

As in the above command execution, it fail with an error message appear.

Solution

Actually, the solution for the above error message causing it is because of the column’s character is not a proper name for a column name. In that case, just change it into a proper one. So, edit the SQL file and find the column’s character or the column name which is the cause for the database restore process to fail. Changing the column name from [product_code] to another proper one. That new column name is ‘product_code’. After editing the file, just execute the process for importing or restoring the data once more as follows :

C:>psql -Uuser_sinergi -d db_sinergi < "C:UsersPersonalDownloadsinsert-current-product.sql"
Password for user db_user:
INSERT 0 556

C:>

Fortunately, the process is a success as in the output of the command above.

В коде «на» есть только в строках, когда задаю текст для отправки телеграм боту, оно вообще никак не связано
60d463102517d803543855.png

using System;
using System.Data;
using Microsoft.Data.Sqlite;
using Telegram;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;


namespace TelegramSQLBotv2
{
    class Program
    {
        static SqliteConnection connection = new SqliteConnection("Data Source=usersdata.db");
        static TelegramBotClient client = new TelegramBotClient("123");
        static void Main(string[] args)
        {
            client.OnMessage += BotOnMessage; 
            client.StartReceiving(); 
            Console.ReadKey();
            client.StopReceiving();
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }
        async static void BotOnMessage(object sender, MessageEventArgs e)
        {
            Message msg = e.Message; //создаём переменную, которая содержит все свойства сообщения
            ParseMode parseMode = ParseMode.Markdown; // Позволяет делать жирный текст и т.п

            #region Keyboards

            var CommonUserKeyboard = new ReplyKeyboardMarkup()
            {
                Keyboard = new[]
                    {
                        new[]
                        {
                            new KeyboardButton("123"),
                            new KeyboardButton("123"),
                        }
                    }
            }; 

            var CommonUserLogin = new ReplyKeyboardMarkup()
            {
                Keyboard = new[]
                   {
                        new[]
                        {
                            new KeyboardButton("Пройти капчу "),
                        }
                    }
            }; /

            #endregion

            #region MainMethods

            if (msg.Text == "/createDB")
            {
                connection.Open();
                SqliteCommand command = new SqliteCommand();
                command.Connection = connection;
                command.CommandText = "CREATE TABLE  MainDataBase(_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, M TEXT NULL)";
                command.ExecuteNonQuery();
                Console.WriteLine("Таблица MainDataBase создана");
                connection.Close();
            } // Созданние базы данных

            if (msg.Text == "/start")
            {
                CommonUserLogin.ResizeKeyboard = true;
                await client.SendTextMessageAsync(msg.Chat.Id, $"Здравствуйте, *{msg.Chat.FirstName}*. Чтобы продолжить - нажмите на кнопку " + "Пройти капчу ", parseMode, replyMarkup: CommonUserLogin);
            } // Первое сообщение

            if (msg.Text == "Пройти капчу ")
            {
                CommonUserKeyboard.ResizeKeyboard = true;
                bool same = false;
                connection.Open();
                string sqlExpression = "SELECT * FROM MainDataBase";
                SqliteCommand command = new SqliteCommand(sqlExpression, connection);
                SqliteDataReader reader = command.ExecuteReader();
                while (reader.Read()) // построчно считываем данные
                {
                    object id = reader.GetValue(0);
                    if (id.ToString() == msg.Chat.Id.ToString())
                    {
                        same = true;
                    }
                }
                reader.Close();
                if (same == true)
                {
                    await client.SendTextMessageAsync(msg.Chat.Id, $"Приветствуем вас снова, пользователь *{msg.Chat.Id}*.", parseMode, replyMarkup: CommonUserKeyboard);
                }
                else
                {
                    SqliteCommand command2 = new SqliteCommand();
                    command.Connection = connection;
                    command.CommandText = $"INSERT INTO MainDataBase (_id, M) VALUES ({msg.Chat.Id.ToString()}, {msg.Chat.FirstName})";
                    command.ExecuteNonQuery();
                    Console.WriteLine($"Новый юзер - {msg.Chat.FirstName}");
                    await client.SendTextMessageAsync(msg.Chat.Id, $"Капча пройдена и аккаунт с id *{msg.Chat.Id}* успешно создан", parseMode, replyMarkup: CommonUserKeyboard);
                }
                connection.Close();
            }
            #endregion

        }

    }
}

Понравилась статья? Поделить с друзьями:
  • Как ошибки перенаправить ошибки в dev null
  • Как ошибки перенаправить в отдельный файл
  • Как ошибки одного становятся примером для другого
  • Как ошибки на дэу леганза
  • Как ошибки климата ауди а6 с5