Меню

Ошибка синтаксиса примерное положение into

Here is my code:

SET SEARCH_PATH TO work

/* Task 1 */

INSERT INTO Category (CategoryID, Name, CategoryType)    

VALUES(1,'English','fiction');

and here is the error:

ERROR:  syntax error at or near "INSERT"
LINE 4: INSERT INTO Category (CategoryID,Name,CategoryType)
          ^
********** Error **********

ERROR: syntax error at or near "INSERT"
SQL state: 42601
Character: 45

a_horse_with_no_name's user avatar

asked Apr 26, 2016 at 21:14

aster's user avatar

3

You need a semi-colon at the end of the SET statement:

SET SEARCH_PATH TO work;

answered Mar 9, 2017 at 18:43

Ray O'Donnell's user avatar

Try to just do an insert into that is schema qualified:

INSERT INTO work.Category (CategoryID, Name, CategoryType)    

VALUES(1,'English','fiction');

Or

SET SEARCH_PATH TO work;

/* Task 1 */

INSERT INTO Category (CategoryID, Name, CategoryType)    

VALUES(1,'English','fiction');

Either should fix the error.

answered Apr 26, 2016 at 21:33

Berra2k's user avatar

Berra2kBerra2k

3182 gold badges5 silver badges14 bronze badges

seneka

7 / 7 / 2

Регистрация: 28.09.2012

Сообщений: 82

1

10.10.2012, 09:17. Показов 13325. Ответов 1

Метки нет (Все метки)


Здравствуйте!!!
Помогите разобраться… Есть код по нажатию на кнопку — происходит добавление в БД
Но выходит исключение
Необработанное исключение типа «System.Data.OleDb.OleDbException» в System.Data.dll
Дополнительные сведения: Ошибка синтаксиса в инструкции INSERT INTO.

сам код

C#
1
2
3
4
5
6
7
8
9
10
11
 OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MeM.accdb");
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "INSERT into MeM (Date, Time, All) VALUES (@Date , @Time, @All)";
            cmd.Connection = conn;
            cmd.Parameters.AddWithValue("@Data", dateTimePicker1.Text);
            cmd.Parameters.AddWithValue("@Time", maskedTextBox1.Text);
            cmd.Parameters.AddWithValue("@All", textBox1.Text);
            conn.Open();
            cmd.ExecuteNonQuery(); // Здесь выдает ошибку о неверной команде Insert 
            conn.Close();

Добавлено через 33 минуты
Всем Спасибо — разобрался Тему можно закрыть )))

C#
1
2
3
4
5
6
7
8
9
10
11
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MeM.accdb");
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "INSERT into MeM (Data_sob, Time_sob) VALUES (@Date , @Time)";
            cmd.Connection = conn;
            cmd.Parameters.AddWithValue("@Date", dateTimePicker1.Text);
            cmd.Parameters.AddWithValue("@Time", maskedTextBox1.Text);
           // cmd.Parameters.AddWithValue("@All", textBox1.Text);
            conn.Open();
            cmd.ExecuteNonQuery(); 
            conn.Close();

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



1



9 / 9 / 5

Регистрация: 08.10.2012

Сообщений: 48

10.10.2012, 17:13

2

У тебя в значениях было @Dat

e

, а в параметры добавил как @Dat

a



0



Проблема даже совсем непонятная. Вроде все правильно но выдает ошибку: Ошибка синтаксиса в инструкции 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#)

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

This might be a little silly, but can’t figure out why this insert is not working, I did surround the IP with single / double quotes!

psql -U dbuser hosts -h dbhost -c 'INSERT INTO HOSTS ('type','name') VALUES ('"test"', '"10.100.133.1"')'
Password for user dbusr:
ERROR:  syntax error at or near ".133"
LINE 1: INSERT INTO HOSTS (type,name) VALUES (test, 10.100.133.1)
                                                          ^

Do I need to escape anything?

asked Oct 24, 2016 at 7:34

Deano's user avatar

2

This works fine:

postgres=# create table hosts ( type varchar(20), name varchar(20));
CREATE TABLE
postgres=# q
postgres@ironforge:~$ psql -c "insert into hosts (type,name) values ('test','10.100.133.1')"
INSERT 0 1
postgres@ironforge:~$

answered Oct 24, 2016 at 8:00

Philᵀᴹ's user avatar

PhilᵀᴹPhilᵀᴹ

31.3k9 gold badges80 silver badges107 bronze badges

1

A couple of notes.

  • you never have to quote columns names (identifiers) and you never should quote them where it isn’t required.
    1. create the table with them unquoted
    2. never quote them in your queries
  • you can always use $$ DOLLAR QUOTED STRING LITERALS to get around shell quoting escaping.

So this should work,

psql -c 'INSERT INTO HOSTS (type,name) VALUES ($$test$$, $$10.100.133.1$$)'

answered Nov 23, 2016 at 18:21

Evan Carroll's user avatar

Evan CarrollEvan Carroll

58.9k42 gold badges216 silver badges442 bronze badges

3

Вот пример из документации

QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
              "VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");
query.exec();

Если вы пытаетесь сделать bind, то вам нужно правильно сформировать строку запроса, плюс указать bind привязки.

В данном случае наличие кавычек уже не нужно будет.

bool DataBase::inserIntoTable(const QVariantList &data)
{

    QSqlQuery query;

   query.prepare("INSERT INTO public.NameTable (FirstName, SurName, Nik) VALUES (:db, 'cc', 'bb');");
   query.bindValue(":db",       data[0].toString());

    if(!query.exec()){
        qDebug() << "error insert into " << TABLE;
        qDebug() <<  query.lastQuery();
        qDebug() << query.lastError().text();
        return false;
    } else {
        return true;
    }
    return false;
}

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

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка синтаксиса примерное положение integer
  • Ошибка сириус сэм 4 message