Why does this statement return a syntax error

Ok I have a very simple mysql database but when i try to run this query via mysql-admin i get weird errors INSERT INTO customreports (study, type, mode, select, description) VALUES ('1', '2'...

Ok I have a very simple mysql database but when i try to run this query via mysql-admin i get weird errors

INSERT INTO customreports (study,
type, mode, select, description)
VALUES (‘1’, ‘2’, ‘3’, ‘4’, ‘5’);

Error:

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 ‘select, description) VALUES (‘1’, ‘2’, ‘3’, ‘4’, ‘5’)’ at line 1

JNK's user avatar

JNK

62.3k15 gold badges121 silver badges137 bronze badges

asked May 26, 2009 at 20:10

The Digital Ninja's user avatar

You’re having problems because you’re using SQL reserved words as column names and not escaping them. Try like this:

INSERT INTO `customreports`
(`study`, `type`, `mode`, `select`, `description`)
VALUES
('1', '2', '3', '4', '5');

answered May 26, 2009 at 20:12

chaos's user avatar

2

Yeah, I would rewrite as:

INSERT INTO [customreports] ([study], [type], [mode], [select], [description]) VALUES (‘1’, ‘2’, ‘3’, ‘4’, ‘5’);

answered May 26, 2009 at 20:14

alex's user avatar

alexalex

9435 silver badges7 bronze badges

just a guess, but is reserved word «select» (listed as a column name) causing a problem?

answered May 26, 2009 at 20:13

KM.'s user avatar

KM.KM.

101k33 gold badges177 silver badges211 bronze badges

2

«SELECT» is a reserved word in SQL… use a different word than «select»

answered May 26, 2009 at 20:13

Jason's user avatar

JasonJason

51k37 gold badges133 silver badges185 bronze badges

The word ‘select’ is reserved in sql. The interpreter thinks you’re trying to use a SELECT statement inside the INSERT INTO statement. You need to enclose the field names so that the interpreter doesn’t read them as commands.

Update for MySQL:

insert into customreports ('study','type','mode','select','description') values...

answered May 26, 2009 at 20:14

Justin Niessner's user avatar

Justin NiessnerJustin Niessner

240k40 gold badges405 silver badges535 bronze badges

Correct per Chaos… but the critical thing to remember is you should do your best to NOT use RESERVED words as column names in a table… such as SELECT and TYPE…. not positive of the other three, but that’s where your conflict is. Yes, by being explicit with quotes around the fields will tell the SQL you mean the field within, but its also best to know WHY its failing, and not just a work-around resolution… helps prevent similar issues in the future.

answered May 26, 2009 at 20:15

DRapp's user avatar

DRappDRapp

47.2k12 gold badges71 silver badges142 bronze badges

Ditto the above, but I believe you need double quotes around the column names, not single quotes. Perhaps some flavors of SQL will process the single quotes correctly, but I think the standard says double quotes for field names, single quotes for field values.

answered May 26, 2009 at 20:31

Jay's user avatar

JayJay

26.6k10 gold badges59 silver badges112 bronze badges

1

I’m using Apatana 3, i modified the JS code formatter a little bit to let it seem more clear, below is the code after format, it give me an error:

    copyOffset : function( index )
    {
        return
        {
            x : index, y : index
        };
    }

firebug give me:

SyntaxError: invalid label

if i change it to:

    copyOffset : function( index )
    {
        return{
            x : index, y : index
        };
    }

will be OK, Anybody who can tell me what’s the diff between these two return statement?

Ted's user avatar

Ted

2,4852 gold badges37 silver badges53 bronze badges

asked Oct 2, 2012 at 9:09

Mike's user avatar

The difference is that the first snippet is actually interpreted as…

copyOffset : function( index )
{
    return;
    {
        x : index, y : index
    };
}

It’s called Automatic Semicolon Insertion: when JavaScript parser sees a statement that seems to be complete, but misses semicolon, it attempts to ‘fix’ it.

And yes, even though helpful at times, it can be quite annoying. This article explains this JavaScript feature in details.

answered Oct 2, 2012 at 9:12

raina77ow's user avatar

raina77owraina77ow

102k14 gold badges193 silver badges227 bronze badges

1

Haha, this is a classical one;)

Javasript breaks on

return
{

because it treats { as a new block and implicitely inserts a semicolon:

return;
{

thus returning undefined:-D

The Problem is Javasript inserting a Semicolon at the end of a line when the statement makes sense. Since return can stand on it’s own, Javascript interprets it as a complete statement and inserts the semicolon, thus breaking your code.

Actually, this is the reason, why in Javascript you alway should avoid those newlines and write:

copyOffset : function( index ){
    return{
        x : index, y : index
    };
}

answered Oct 2, 2012 at 9:13

Christoph's user avatar

ChristophChristoph

49.2k20 gold badges99 silver badges128 bronze badges

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

«Пусть у нас есть функция f(x,y) = xy, которая перемножает два аргумента и возвращает полученное значение».

Программист садится и пишет код:

a = 10
b = 15
result = 0
def fun(x,y): 
    return x y
result = fun(a,b)
print(result)

Но при выполнении такого кода компьютер выдаёт ошибку:

File "main.py", line 13
result = x y
^
❌ SyntaxError: invalid syntax

Почему так происходит: в каждом языке программирования есть свой синтаксис — правила написания и оформления команд. В Python тоже есть свой синтаксис, по которому для умножения нельзя просто поставить рядом две переменных, как в математике. Интерпретатор находит первую переменную и думает, что ему сейчас объяснят, что с ней делать. Но вместо этого он сразу находит вторую переменную. Интерпретатор не знает, как именно нужно их обработать, потому что у него нет правила «Если две переменные стоят рядом, их нужно перемножить». Поэтому интерпретатор останавливается и говорит, что у него лапки. 

Что делать с ошибкой SyntaxError: invalid syntax

В нашем случае достаточно поставить звёздочку (знак умножения в Python) между переменными — это оператор умножения, который Python знает:

a = 10
b = 15
result = 0
def fun(x,y): 
    return x * y
result = fun(a,b)
print(result)

В общем случае найти источник ошибки SyntaxError: invalid syntax можно так:

  1. Проверьте, не идут ли у вас две команды на одной строке друг за другом.
  2. Найдите в справочнике описание команды, которую вы хотите выполнить. Возможно, где-то опечатка.
  3. Проверьте, не пропущена ли команда на месте ошибки.

Практика

Попробуйте найти ошибки в этих фрагментах кода:

x = 10 y = 15
def fun(x,y): 
    return x * y
try:  
    a = 100
    b = "PythonRu"
    assert a = b
except AssertionError:  
    print("Исключение AssertionError.")
else:  
    print("Успех, нет ошибок!")

Вёрстка:

Кирилл Климентьев

Software errors are prevalent. It’s easy to make them, and it’s hard to find them. In this chapter, we’ll explore topics related to the finding and removal of bugs within our C++ programs, including learning how to use the integrated debugger that is part of our IDE.

Although debugging tools and techniques aren’t part of the C++ standard, learning to find and remove bugs in the programs you write is an extremely important part of being a successful programmer. Therefore, we’ll spend a bit of time covering such topics, so that as the programs you write become more complex, your ability to diagnose and remedy issues advances at a similar pace.

If you have experience from debugging programs in another compiled programming language, much of this will be familiar to you.

Syntax and semantic errors

Programming can be challenging, and C++ is somewhat of a quirky language. Put those two together, and there are a lot of ways to make mistakes. Errors generally fall into one of two categories: syntax errors, and semantic errors (logic errors).

A syntax error occurs when you write a statement that is not valid according to the grammar of the C++ language. This includes errors such as missing semicolons, using undeclared variables, mismatched parentheses or braces, etc… For example, the following program contains quite a few syntax errors:

#include <iostream>

int main()
{
    std::cout < "Hi there"; << x << 'n'; // invalid operator (<), extraneous semicolon, undeclared variable (x)
    return 0 // missing semicolon at end of statement
}

Fortunately, the compiler will generally catch syntax errors and generate warnings or errors, so you easily identify and fix the problem. Then it’s just a matter of compiling again until you get rid of all the errors.

Once your program is compiling correctly, getting it to actually produce the result(s) you want can be tricky. A semantic error occurs when a statement is syntactically valid, but does not do what the programmer intended.

Sometimes these will cause your program to crash, such as in the case of division by zero:

#include <iostream>

int main()
{
    int a { 10 };
    int b { 0 };
    std::cout << a << " / " << b << " = " << a / b << 'n'; // division by 0 is undefined
    return 0;
}

More often these will just produce the wrong value or behavior:

#include <iostream>

int main()
{
    int x;
    std::cout << x << 'n'; // Use of uninitialized variable leads to undefined result

    return 0;
}

or

#include <iostream>

int add(int x, int y)
{
    return x - y; // function is supposed to add, but it doesn't
}

int main()
{
    std::cout << add(5, 3) << 'n'; // should produce 8, but produces 2

    return 0;
}

or

#include <iostream>

int main()
{
    return 0; // function returns here

    std::cout << "Hello, world!n"; // so this never executes
}

Modern compilers have been getting better at detecting certain types of common semantic errors (e.g. use of an uninitialized variable). However, in most cases, the compiler will not be able to catch most of these types of problems, because the compiler is designed to enforce grammar, not intent.

In the above example, the errors are fairly easy to spot. But in most non-trivial programs, semantic errors are not easy to find by eyeballing the code. This is where debugging techniques can come in handy.

Я использую Apatana 3, я немного изменил форматировщик кода JS, чтобы он выглядел более понятным, ниже приведен код после форматирования, он дает мне ошибку:

    copyOffset : function( index )
    {
        return
        {
            x : index, y : index
        };
    }

поджигатель дай мне:

SyntaxError: invalid label

если я изменю его на:

    copyOffset : function( index )
    {
        return{
            x : index, y : index
        };
    }

все будет в порядке. Кто-нибудь может сказать мне, в чем разница между этими двумя операторами возврата?

2 ответы

Разница в том, что первый фрагмент на самом деле интерпретируется как…

copyOffset : function( index )
{
    return;
    {
        x : index, y : index
    };
}

Это называется Автоматическая вставка точки с запятой: когда синтаксический анализатор JavaScript видит оператор, который кажется завершенным, но пропускает точку с запятой, он пытается «исправить» его.

И да, хотя иногда это полезно, это может быть довольно раздражающим. Эта статья подробно объясняет эту функцию JavaScript.

ответ дан 02 окт ’12, 10:10

Ха-ха, это классика ;)

Javasript ломается

return
{

потому что лечит { как новый блок и неявно вставляет точку с запятой:

return;
{

таким образом возвращая undefined :-D

Проблема заключается в том, что Javasript вставляет точку с запятой в конце строки, когда оператор имеет смысл. С return может стоять сам по себе, Javascript интерпретирует его как завершенный оператор и вставляет точку с запятой, тем самым нарушая ваш код.

Собственно, по этой причине в Javascript всегда следует избегать этих новых строк и писать:

copyOffset : function( index ){
    return{
        x : index, y : index
    };
}

ответ дан 02 окт ’12, 10:10

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

javascript
aptana3

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

“SyntaxError: Illegal return statement” in JavaScript is a syntax-related error. It describes that you are typing the command wrong or using the statement in the wrong place. Please read the following instructions to resolve it.

The most common reason for “SyntaxError: Illegal return statement” in Javascript is that you used the return statement incorrectly. As the error code describes, it’s a syntax-related error, indicating it’s a return statement. See the example below to better understand.

Here I have a very simple example: if the condition in the learn() function is true, then a corresponding message is sent. But if I leave the return statement out of the function, it throws an error like this:

var slogan = "LearnShareIT"

function learn() {
    if (slogan == "LearnShareIT") {        
        return "I am a developer!!";        
    }  
}

//returns in the wrong place
return "I am a student!!";

console.log(learn());

Output

main.js:173 Uncaught SyntaxError: Illegal return statement (at main.js:173:1)

Or if I am missing a curly brace, it still gives me the same error:

var slogan = "LearnShareIT"

function learn() //missing here{        
    return slogan;        
}

console.log(learn());

Output

Uncaught SyntaxError: Illegal return statement (at main.js:171:5)

Since a return statement follows the curly brace, it will still report an error.

To return an appropriate value to the function without causing an error, refer to the way below.

How to fix this error?

Use the correct command structure

Also the above example, I proceed to reset the position of the return command, and immediately it shows the result I want as follows:

var slogan = "LearnShareIT"

function learn() {
    if (slogan == "LearnShareIT") {        
        return "I am a developer!!";        
    }
  
//put the return command in the right place
    return "I am a student!!";
}

console.log(learn());

Output

I am a developer!!

For the missing function brackets, we need to add the correct syntax, and the code will run smoothly:

var slogan = "LearnShareIT"

function learn() {        
    return slogan;        
}

console.log(learn());

Output

LearnShareIT

Shorten the number of return statements

Too many return statements in a function will cause trouble for your code. Return is a command directly related to the computer’s memory. If you abuse it, you will get an error.

Example

var fruit = 'apple';

function learn() {
    if (fruit == 'apple') {
        return 'apple';
    } 
    else {
        return 'banana';
    }

//returns in the wrong place
    return 'orange';

//returns in the wrong place
}return 'melon';

Output

main.js:186 Uncaught SyntaxError: Illegal return statement (at main.js:186:2)

Using too many return statements will mess up the code and you might end up putting it in the wrong place, so shorten it like this:

var fruit = 'apple';

function choose() {
    if (fruit == 'apple') {
        return 'apple';
    } 
    else {
        return 'banana';
    }
}

console.log(choose());

Output

apple

Summary

For the error “SyntaxError: Illegal return statement” in JavaScript, you need to understand what you want your function to return so you can use return correctly. Using return indiscriminately poses a huge risk to your code, so be aware. Above are solutions to help you solve this error, good luck with your studies.

Maybe you are interested:

  • TypeError: indexOf is not a function in JavaScript
  • SyntaxError: Unexpected token in JavaScript

Tom

My name is Tom Joseph, and I work as a software engineer. I enjoy programming and passing on my experience. C, C++, JAVA, and Python are my strong programming languages that I can share with everyone. In addition, I have also developed projects using Javascript, html, css.

Job: Developer
Name of the university: UTC
Programming Languages: C, C++, Javascript, JAVA, python, html, css

Python can only execute a program if the program is syntactically correct;
otherwise, the process fails and returns an error message. Syntax refers
to the structure of a program and the rules about that structure. For example,
in English, a sentence must begin with a capital letter and end with a period.
this sentence contains a syntax error. So does this one

In Python, rules of syntax include requirements like these: strings must be enclosed in quotes; statements must
generally be written one per line; the print statement must enclose the value to be displayed in parenthesis;
expressions must be correctly formed. The following lines contain syntax errors:

print(Hello, world!)
print "Hello, world!"
print(5 + )

For most readers of English, a few syntax errors are not a significant problem, which is why we can read the poetry of
e. e. cummings without problems. Python is not so forgiving. When you run a Python program, the interpreter checks it
for syntax errors before beginning to execute the first statement. If there is a single syntax error anywhere in your
program, Python will display an error message and quit without executing any of the program.

To see a syntax error in action, look at the following program. Can you spot the error?
After locating the error, run the program to see the error message.

Notice the following:

  1. The error message clearly indicates that the problem is a SyntaxError. This lets you know the problem
    is not one of the other two types of errors we’ll discuss shortly.

  2. The error is on line 2 of the program. However, even though there is nothing
    wrong with line 1, the print statement does not execute — none of the program successfully executes
    because of the presence of just one syntax error.

  3. The error gives the line number where Python believes the error exists. In this case, the error message pinpoints the
    location correctly. But in other cases, the line number can be inaccurate or entirely missing.

    To see an example of the latter, try removing just the right parenthesis ) from line 2 and
    running the program again. Notice how the error message gives no line number at all. With syntax errors, you need to be
    prepared to hunt around a bit in order to locate the trouble.

One aspect of syntax you have to watch out for in Python involves indentation. Python requires you to begin all
statements at the beginning of the line, unless you are using a flow control statement like a for or an if statement
(we’ll discuss these soon… stay tuned!). To see an example of this kind of problem, modify the program above by inserting a
couple of spaces at the beginning of one of the lines.

Check your understanding

    Which of the following is a syntax error?

  • Attempting to divide by 0.
  • A syntax error is an error in the structure of the python code that can be detected before the program is executed. Python cannot usually tell if you are trying to divide by 0 until it is executing your program (e.g., you might be asking the user for a value and then dividing by that value—you cannot know what value the user will enter before you run the program).
  • Forgetting a colon at the end of a statement where one is required.
  • This is a problem with the formal structure of the program. Python knows where colons are required and can detect when one is missing simply by looking at the code without running it.
  • Forgetting to divide by 100 when printing a percentage amount.
  • This will produce the wrong answer, but Python will not consider it an error at all. The programmer is the one who understands that the answer produced is wrong.

    Who or what typically finds syntax errors?

  • The programmer.
  • Programmers rarely find all the syntax errors, there is a computer program that will do it for us.
  • The compiler / interpreter.
  • The compiler and / or interpreter is a computer program that determines if your program is written in a way that can be translated into machine language for execution.
  • The computer.
  • Well, sort of. But it is a special thing in the computer that does it. The stand alone computer without this additional piece can not do it.
  • The teacher / instructor.
  • Your teacher and instructor may be able to find most of your syntax errors, but only because they have experience looking at code and possibly writing code. With experience syntax errors are easier to find. But we also have an automated way of finding these types of errors.

You have attempted of activities on this page

Понравилась статья? Поделить с друзьями:
  • Whoa cyberpunk 2077 has flatlined как исправить
  • Who ya extended error code
  • Who has invented paper ошибка
  • Whitelabel error page как исправить
  • Whitelabel error page госуслуги при оплате госпошлины 405