2 / 2 / 1
Регистрация: 06.10.2021
Сообщений: 58
1
11.10.2022, 23:35. Показов 400. Ответов 0
Выполняю некоторое задание по вузу, в ERBuilder создаются таблицы, связи между ними задаются, добавляются последовательности(или триггеры), чтоб первичный ключ постоянно назначался сам при добавлении записи, и добавляются функции на удаление, добавление или обновление записей в таблице. При попытке переноса готовой БД из ERBuilder в pgadmin4 (PostgreSQL 13) выдаёт такую ошибку. При этом, таблицы со всеми колонками и ключами создаются в БД, но перенос ломается либо на стадии создания функций вставки, удаления и обновления, либо на стадии создания последовательности. Не понимаю, как устранить ошибку, пробовал по-разному писать данное выражение, пробовал добавлять название в скобки, добавлял начальное значение, от которого стартует отсчёт последовательности( «START 0» ввёл после названия) .Ниже будут некоторые скрипты, которые относятся к проблеме
Скрипт создания таблицы
SQL | ||
|
Скрипт триггера для таблицы Postavshik
SQL | ||
|
После первых же строк данного триггера мне выдаёт ошибку, дословно:
«CREATE SEQUENCE id_postavshik_gen
ошибка синтаксиса (примерное положение: ‘CREATE’)»
Добавлено через 16 минут
ШТОШ, проблема в том, что нет «;» после кжадй процедуры, из-за этого CREATE он не понимал
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
Hey everyone I need some help with creating tables. I have the script below and it creates a few tables. When i try to run the script it give me this error:
psql:script.sql:10: ERROR: syntax error at or near "Group"
LINE 6: CREATE TABLE Group(
Can anyone tell me what is going on?
CREATE TABLE Group(
name varchar(40) PRIMARY KEY NOT NULL
);
CREATE TABLE Artist(
name varchar(30) PRIMARY KEY NOT NULL,
birthplace varchar(20) NOT NULL,
age int NOT NULL CHECK (age > 0),
style varchar(20) NOT NULL
);
CREATE TABLE Artwork(
title varchar(40) PRIMARY KEY NOT NULL,
artist varchar(30) NOT NULL references Artist(name),
group_name varchar(40) NOT NULL references Group(name),
year int NOT NULL CHECK (year > 0),
type varchar(30) NOT NULL,
price money NOT NULL,
);
CREATE TABLE Customer(
cust_id int PRIMARY KEY NOT NULL,
name varchar(40) NOT NULL,
address varcahr(60) NOT NULL,
amount money NOT NULL CHECK(amount > 0),
like_artist varchar(30) NOT NULL references Artist(name),
like_group varchar(40) NOT NULL references Group(name)
);
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»;
Пытаюсь создать табличку, вот такую
CREATE TABLE screens_items ( screenitemid bigint NOT NULL, screenid bigint NOT NULL, resourcetype integer DEFAULT '0' NOT NULL, resourceid bigint DEFAULT '0' NOT NULL, width integer DEFAULT '320' NOT NULL, height integer DEFAULT '200' NOT NULL, x integer DEFAULT '0' NOT NULL, y integer DEFAULT '0' NOT NULL, colspan integer DEFAULT '0' NOT NULL, rowspan integer DEFAULT '0' NOT NULL, elements integer DEFAULT '25' NOT NULL, valign integer DEFAULT '0' NOT NULL, halign integer DEFAULT '0' NOT NULL, style integer DEFAULT '0' NOT NULL, url varchar(255) DEFAULT '' NOT NULL, dynamic integer DEFAULT '0' NOT NULL, sort_triggers integer DEFAULT '0' NOT NULL, application varchar(255) DEFAULT '' NOT NULL, PRIMARY KEY (screenitemid) );
Получаю
Error: ОШИБКА: ошибка синтаксиса (примерное положение: "application")
psql --version psql (PostgreSQL) 9.4.9
Вроде слово «application» не зарезервировано?
← →
alex_1234 ©
(2005-10-10 14:46)
[0]
Строка подключения:
dbIK.ConnectionString:=
"Provider=MSDASQL.1;Persist Security Info=False;"+
"Extended Properties="DSN=Ôàéëû dBASE;DBQ="+
PathIK+";DefaultDir="+PathIK+";DriverId=533;"+
"MaxBufferSize=2048;PageTimeout=5;"";
где PathIK — содержит путь к папке с таблицами.
При попытке выполнить запрос:
q2.Close;
q2.SQL.Clear;
q2.SQL.Add("CREATE TABLE PLUCASH(");
q2.SQL.Add("ARTICUL char(30),");
q2.SQL.Add("NAME char(80),");
q2.SQL.Add("MESURIMENT char(10),");
q2.SQL.Add("MESPRESISI NUMERIC(16,6)");
q2.SQL.Add(")");
q2.ExecSQL;
ругается следующим макаром:
....Ошибка синтаксиса в инструкции CREATE TABLE....
← →
alex_1234 ©
(2005-10-10 14:52)
[1]
Забыл написать:
ориентировочно ошибка в q2.SQL.Add(«MESPRESISI NUMERIC(16,6)»);
т.к. без этого поля все прекрасно создается.
А БДЕ — (СКуэЛь експлорер) — все прекрасно работает
← →
Reindeer Moss Eater ©
(2005-10-10 14:56)
[2]
А БДЕ — (СКуэЛь експлорер) — все прекрасно работает
Работает, потому что в LocalSQL есть такой тип поля.
← →
alex_1234 ©
(2005-10-10 15:00)
[3]
Но ведь не может быть такого, чтобы в ADO не было аналогичного типа….
Подскажите, в каком хлп-файле нарыть типы полей поддерживаемых АДО…
← →
sniknik ©
(2005-10-10 15:38)
[4]
> CREATE TABLE PLUCASH … ARTICUL …
;о) супермаг dos. ;о)
просто
MESPRESISI NUMERIC
и все без всяких (16,6). поддерживается только емулируемый тип (под double) с размерностью 20,5 который и будет создан по умолчанию. без указаний.
но это тебе конечно не поможет. -> супермаг… %о)
> в каком хлп-файле нарыть типы полей поддерживаемых АДО…
Jet — JETSQL40.CHM. а АДО поддерживает все что поддерживает подключаемый драйвер/провайдер. кроме разных мелких досадных недоразумений. (бигинт…)
← →
mr.il ©
(2005-10-10 15:47)
[5]
Попробуй прописать название таблицы с расширением — PLUCASH.dbf.
← →
alex_1234 ©
(2005-10-10 16:04)
[6]
mr.il : писал — не выходит каменный цветок.
Попробую как писал sniknik — а вдруг «съест»
← →
Reindeer Moss Eater ©
(2005-10-10 16:56)
[7]
Но ведь не может быть такого, чтобы в ADO не было аналогичного типа….
Почему не может? Может. Зависит от завихрений автора используемого провайдера. Кроме того, этот типа там может просто называться по другому.
← →
Reindeer Moss Eater ©
(2005-10-10 16:58)
[8]
Судя по всему у тебя провайдер использует ODBC.
Вот и посмотри как по стандарту ODBC зовется такое поле.
← →
Anatoly Podgoretsky ©
(2005-10-10 18:55)
[9]
Reindeer Moss Eater © (10.10.05 16:58) [8]
Не судя по всему, а так и есть MSDASQL
← →
alex_1234 ©
(2005-10-11 16:23)
[10]
Блин, как бы мне этого не хотелось — а пришлось делать через «ж..у»:
dbMag.ConnectionString:=
"Provider=MSDASQL.1;Persist Security Info=False;"+
"Extended Properties="DSN=Òàáëèöû Visual FoxPro;UID=;"+
"SourceDB="+PathMag+";SourceType=DBF;Exclusive=No;"+
"BackgroundFetch=Yes;Collate=Machine;Null=Yes;"+
"Deleted=Yes;"";
dbIK.ConnectionString:=
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+PathIK+
";Extended Properties=dBase IV;Persist Security Info=False";
т.е. для разных запросов — разные типы полключения:
для таблиц FoxPro — MSDASQL,
а для dBase — Microsoft.Jet.OLEDB
Утешает, что в предыдущих версиях был еще БДЕ, а тут его не будет…
← →
sniknik ©
(2005-10-11 17:39)
[11]
> был еще БДЕ, а тут его не будет…
будет!!! ;о)) оно живее всех живых. Jet использует BDE. полное если стоит, либо урезаное(лайт версия унутрях) если нет.
← →
alex_1234 ©
(2005-10-11 17:53)
[12]
Да я бы все на БДЕ делал-бы (да и в комплект 4 СуперМага она входит), но она не хочет делать один запрос (4 таблички вяжутся, правда весьма несложно) — ругается на индексный файл (таблица Фокса)….
Выполняю некоторое задание по вузу, в ERBuilder создаются таблицы, связи между ними задаются, добавляются последовательности(или триггеры), чтоб первичный ключ постоянно назначался сам при добавлении записи, и добавляются функции на удаление, добавление или обновление записей в таблице. При попытке переноса готовой БД из ERBuilder в pgadmin4 (PostgreSQL 13) выдаёт такую ошибку. При этом, таблицы со всеми колонками и ключами создаются в БД, но перенос ломается либо на стадии создания функций вставки, удаления и обновления, либо на стадии создания последовательности. Не понимаю, как устранить ошибку, пробовал по-разному писать данное выражение, пробовал добавлять название в скобки, добавлял начальное значение, от которого стартует отсчёт последовательности( «START 0» ввёл после названия) .Ниже будут некоторые скрипты, которые относятся к проблеме
Скрипт создания таблицы
SQL | ||
|
Скрипт триггера для таблицы Postavshik
SQL | ||
|
После первых же строк данного триггера мне выдаёт ошибку, дословно:
«CREATE SEQUENCE id_postavshik_gen
ошибка синтаксиса (примерное положение: ‘CREATE’)»
Добавлено через 16 минут
ШТОШ, проблема в том, что нет «;» после кжадй процедуры, из-за этого CREATE он не понимал
I am trying to create database android_api and table users but I am getting error
#1064 - Something is wrong in your syntax near 'use android_api
create table 'users'(
id int(11) NOT NULL primary KEY AU' w linii 3
Here is the code
create database android_api
use android_api
create table users(
id int(11) NOT NULL primary KEY AUTO_INCREMENT,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);
asked Dec 4, 2016 at 13:21
1
You should separate each SQL statement with ;
, otherwise your syntax is incorrect.
Here is the correct syntax:
create database android_api;
use android_api;
create table users(
id int(11) NOT NULL primary KEY AUTO_INCREMENT,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);
In your code what you did was actually:
create database android_api use android_api
(Which is not a valid CREATE
statement).
answered Dec 4, 2016 at 13:41
DekelDekel
60.8k10 gold badges101 silver badges129 bronze badges
9
Actually, the accepted answer is enough. This is a very small idea to share after running into the same problem as you report it, but in a beginner’s tutorial Load PostgreSQL Sample Database in an SQL Shell.
In general, if you have the reported error in an SQL shell, and if you are not sure whether you have typed ;
at the end of the last line, just type ;
as a new command and press Enter to be sure that you type your next command in LINE 1
and not in LINE 2
.
Without this «trick», some stupidity like this can happen:
postgres=# CREATE DATABASE dvdrental
postgres-# show databases
postgres-# create database dvdrental;
ERROR: syntax error at or near »show«
LINE 2: show databases
^
postgres=# create database dvdrental
postgres-# CREATE DATABASE dvdrental;
ERROR: syntax error at or near »CREATE«
LINE 2: CREATE DATABASE dvdrental;
^
postgres=# CREATE DATABASE dvdrental;
CREATE DATABASE
Finally working, as can be seen by the output CREATE DATABASE
.
answered May 30, 2021 at 23:02
questionto42questionto42
7,2054 gold badges57 silver badges90 bronze badges
1
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»;
Всем привет хочу создать таблицу в postgresql через python но возникает ошибка( cur.execute(«»»CREATE TABLE {}
psycopg2.errors.SyntaxError: ОШИБКА: ошибка синтаксиса (примерное положение: «688093622»)) вот код:
if user_id_v not in mas_user_id:
mas_user_id.append(user_id_v)
print('Новый пользователь БОТА: ', mas_user_id[-1])
conn = psycopg2.connect(
host='localhost',
database='',
user='',
password='',
port=5432
)
cur = conn.cursor()
# Создание таблицы
# Создание таблицы
cur.execute(f'''CREATE TABLE {user_id}
(ADMISSION INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
COURSE CHAR(50),
DEPARTMENT CHAR(50));''')
print("Table created successfully")
conn.commit()
conn.close()
conn.commit()
conn.close()