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
62.9k15 gold badges121 silver badges138 bronze badges
asked May 26, 2009 at 20:10
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
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
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.KM.
101k34 gold badges178 silver badges212 bronze badges
2
«SELECT» is a reserved word in SQL… use a different word than «select»
answered May 26, 2009 at 20:13
JasonJason
51.3k37 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 NiessnerJustin Niessner
241k40 gold badges406 silver badges536 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
DRappDRapp
47.4k12 gold badges72 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
JayJay
26.8k10 gold badges60 silver badges112 bronze badges
1
DDim1000 3 / 3 / 0 Регистрация: 17.12.2011 Сообщений: 506 |
||||
1 |
||||
03.01.2017, 13:03. Показов 2199. Ответов 8 Метки нет (Все метки)
Подскажите пожалуйста, что ни так с синтаксисом?
0 |
Модератор 4204 / 3044 / 581 Регистрация: 21.01.2011 Сообщений: 13,177 |
|
03.01.2017, 13:21 |
2 |
‘;., Иванов, Иван, Иванович’ У тебя ругается на значение переменных, а ты показываешь их названия.
0 |
DDim1000 3 / 3 / 0 Регистрация: 17.12.2011 Сообщений: 506 |
||||
03.01.2017, 13:46 [ТС] |
3 |
|||
У тебя ругается на значение переменных, а ты показываешь их названия.
0 |
3 / 3 / 0 Регистрация: 17.12.2011 Сообщений: 506 |
|
03.01.2017, 14:06 [ТС] |
4 |
И так тоже ошибка… Почему?…….: Миниатюры
0 |
Супер-модератор 8783 / 2536 / 144 Регистрация: 07.03.2007 Сообщений: 11,873 |
|
03.01.2017, 14:39 |
5 |
DDim1000, почитайте про параметризированные запросы… а еще неплохо бы увидеть текст запроса со значениями… хотя есть некая уверенность, что не хватает кавычек для строк и дат… Подготавливаемые запросы
0 |
3 / 3 / 0 Регистрация: 17.12.2011 Сообщений: 506 |
|
03.01.2017, 15:20 [ТС] |
6 |
а еще неплохо бы увидеть текст запроса со значениями… хотя есть некая уверенность, что не хватает кавычек для строк и дат… Что за текст запроса? Где его брать?……
0 |
Lord_Voodoo Супер-модератор 8783 / 2536 / 144 Регистрация: 07.03.2007 Сообщений: 11,873 |
||||
03.01.2017, 17:21 |
7 |
|||
DDim1000,
вот этот запрос приводит к упомянутой выше ошибке?
0 |
DDim1000 3 / 3 / 0 Регистрация: 17.12.2011 Сообщений: 506 |
||||
03.01.2017, 17:42 [ТС] |
8 |
|||
Может кому то пригодиться…
1 |
Супер-модератор 8783 / 2536 / 144 Регистрация: 07.03.2007 Сообщений: 11,873 |
|
03.01.2017, 17:54 |
9 |
DDim1000, вы бы все-таки почитали за параметризированные запросы… ну и про особенности формирования запросов в зависимости от различных типов данных…
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
03.01.2017, 17:54 |
Помогаю со студенческими работами здесь Ошибка синтаксиса Вот сам код: Ошибка синтаксиса create table…
SELECT ‘For the city ‘, city, ‘, the highest rating is ‘, ", Ошибка синтаксиса в триггере UPDATE `journal` SET (`time_end` = NEW.`time_end`) Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 9 |
I have this:
CREATE TABLE people
(
id bigserial,
timestamp timestamptz DEFAULT now() NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE "personal information"
(
id bigserial,
"person id" bigint NOT NULL,
timestamp timestamptz DEFAULT now() NOT NULL,
"data's timestamp" timestamptz,
"field" text NOT NULL,
"value" text,
PRIMARY KEY (id),
FOREIGN KEY ("person id") REFERENCES people (id) ON UPDATE CASCADE ON DELETE CASCADE
);
INSERT INTO people RETURNING id; -- Syntax error.
INSERT INTO people; -- Syntax error.
Why do my INSERTS fail? It’s a fact that all the columns in the «people» table are automatic: the id
column is a bigserial, and the timestamp
one is always set to the current time when it was inserted. Thus, there is no need for me to specify any columns to be inserted, as all of them are automatic.
So why is it a syntax error? What does it want me to do? This makes me feel as if I’m not doing this right somehow, but having a bunch of «personal data» fields in the «people» table would be redundant since that data will be stored in the «personal information» table. For example, the «field» might be «social security number» or «first name», so I just grab whatever record is the latest (based on timestamp) for that «person id» to get their social security number or first name.
If I were to store those values as columns in «people», it would be pointless redundancy, and it would make it a major PITA whenever I introduce a new kind of «personal information field» in the future, as I’d have to add columns to the «people» table. So I really hope that my efficient and smart (IMO) structure is not somehow incompatible with PostgreSQL, and that I’m just missing some minor syntax detail.
$sql = "INSERT INTO user(id, browser, group)
VALUES (NULL, '$user', '$table')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
testtableError: INSERT INTO user(id, browser, group) VALUES (NULL, ‘test’, ‘table’)
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 ‘group) VALUES (NULL, ‘test’, ‘table’)’ at line 1
Ничего не понимаю. Всё проверил уже сто раз. Точно такие же запросы прекрасно работают с другими таблицами. Почему MySQL решил покапризничать?
Проблема даже совсем непонятная. Вроде все правильно но выдает ошибку: Ошибка синтаксиса в инструкции INSERT INTO.
(База на MS Access)
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password='';Data Source=myFirma.mdb"); OleDbCommand myData = new OleDbCommand("select * from Users", myConnection); OleDbCommand myQuery = new OleDbCommand("insert into Users (name,surname,login,password,action)values('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "')",myConnection); myConnection.Open(); myQuery.ExecuteNonQuery(); myConnection.Close();
Попробовал другой вариант:
String myConn = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=myDataBase.mdb;"; String myQuery = "INSERT INTO Users ( name, surname, login, password, action) VALUES ('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "')"; OleDbConnection cn = new OleDbConnection(myConn); cn.Open(); OleDbCommand cmd = new OleDbCommand(myQuery, cn); cmd.ExecuteNonQuery(); cn.Close();
Кроме этих пробовал еще варианты, обыскал весь Гугл, ниче не помогло. Все время одна и та же ошибка на одной и той же строчке:
.ExecuteNonQuery();
Ошибка: Ошибка синтаксиса в инструкции INSERT INTO.
Последняя надежна на вас.
-
Перемещено
1 октября 2010 г. 22:40
MSDN Forums consolidation (От:Visual C#)