I have used the next SQL statement in both MySQL and PostgreSQL, but it fails in PostgreSQL
db.Query(`SELECT COUNT(*) as N FROM email WHERE address = ?`, email)
with this error:
pq: F:"scan.l" M:"syntax error at end of input" S:"ERROR" C:"42601" P:"50" R:"scanner_yyerror" L:"993"
What’s the problem? The error messages in PostgreSQL are very cryptic.
asked Oct 29, 2012 at 10:26
2
You haven’t provided any details about the language/environment, but I’ll try a wild guess anyway:
MySQL’s prepared statements natively use ?
as the parameter placeholder, but PostgreSQL uses $1
, $2
etc. Try replacing the ?
with $1
and see if it works:
WHERE address = $1
The error messages in PostgreSQL are very cryptic.
In general, I’ve found that Postgres error messages are better than competing products (ahem, MySQL and especially Oracle), but in this instance you’ve managed to confuse the parser beyond sanity.
answered Oct 29, 2012 at 10:32
intgrintgr
19.6k5 gold badges59 silver badges68 bronze badges
3
In golang for queries we have use
- MySQL uses the ? variant
- PostgreSQL uses an enumerated $1, $2, etc bindvar syntax
- SQLite accepts both ? and $1 syntax
- Oracle uses a :name syntax
answered Feb 8, 2020 at 0:01
refrazulrefrazul
1111 silver badge3 bronze badges
1
You are using Go right?
try:
db.Query(`SELECT COUNT(*) as N FROM email WHERE address = $1`, email)
answered Oct 29, 2012 at 10:32
simonmenkesimonmenke
2,81919 silver badges28 bronze badges
1
In my case, it was due to using a — line comment where the program that was responsible for interacting with the database read in the multiple lines of my query all as one giant line. This meant that the line comment corrupted the remainder of the query. The fix was to use a /* block comment */ instead.
answered Apr 7, 2020 at 22:40
calamaricalamari
3292 silver badges8 bronze badges
Another possibility — check for any missing END
directives for IF
, LOOP
, etc.
I’d been working in a loop so long, that I didn’t realize I never put in an END LOOP;
.
The message that Postgres displays:
ERROR: syntax error at end of input
LINE 123: $$;
is terribly unhelpful at telling you if some construct was never closed.
answered Apr 12 at 21:38
RandallRandall
2,8101 gold badge21 silver badges24 bronze badges
В синтаксисе ошибка, например имя таблицы может содержать пробел, или строка может иметь символ который неправильно интерпретируется.
Для примера операция Дэлит:
Такой синтакисис не работает, тут понятно, когда вставляешь запрос в средство работы с БД, кути генерирует ту же ошибку:
const QString request="DELETE FROM "" + tableName + "" WHERE name=""+rowName+"";";
Такой синтаксис работает:
const QString request="DELETE FROM "" + tableName + """ +
" WHERE name='"+ rowName +"'";
И пример с инсертом:
Не работает:
const QString request="INSERT INTO "" + tableName +"" ( name ) VALUES ( "+ rowName + " );";
Вроде бы должен работать, скопировав в DataGrid все выполняется:
const QString request="INSERT INTO "" + tableName+ "" (name) "+
"VALUES ('"+ rowName+ "'); ";
И снова нет.
Вот рабочий вариант:
const QString request="INSERT INTO ""+ tableName+"""+
" ( name ) VALUES (?)";
query.prepare(request);
query.bindValue(0, rowName);
Порой не угадаешь почему запрос не работает. Аналогичный, один в один, скопированный в pgAdmin или Датагрид выполняется на ура. Именно поэтому вместо чистого sql запроса лучше использовать ORM
Я использовал следующий оператор SQL как в MySQL, так и в PostgreSQL, но он не работает в PostgreSQL.
db.Query(`SELECT COUNT(*) as N FROM email WHERE address = ?`, email)
с этой ошибкой:
pq: F:"scan.l" M:"syntax error at end of input" S:"ERROR" C:"42601" P:"50" R:"scanner_yyerror" L:"993"
В чем проблема? Сообщения об ошибках в PostgreSQL очень загадочные.
person
Community
schedule
29.10.2012
source
источник
Ответы (4)
Вы не предоставили никаких подробностей о языке / среде, но я все равно попробую предположить:
Подготовленные операторы MySQL изначально используют ?
в качестве заполнителя параметра, но PostgreSQL использует $1
, $2
и т. Д. Попробуйте заменить ?
на $1
и посмотрите, работает ли это:
WHERE address = $1
Сообщения об ошибках в PostgreSQL очень загадочные.
В общем, я обнаружил, что сообщения об ошибках Postgres лучше, чем у конкурирующих продуктов (кхм, MySQL и особенно Oracle), но в этом случае вам удалось запутать синтаксический анализатор сверх разумности.
person
intgr
schedule
29.10.2012
Вы используете Go, верно?
пытаться:
db.Query(`SELECT COUNT(*) as N FROM email WHERE address = $1`, email)
person
simonmenke
schedule
29.10.2012
В golang для запросов мы используем
- MySQL использует? вариант
- PostgreSQL использует синтаксис bindvar с перечислением $ 1, $ 2 и т. Д.
- SQLite принимает оба? и синтаксис $ 1
- Oracle использует синтаксис: name
person
refrazul
schedule
08.02.2020
В моем случае это произошло из-за использования строчного комментария, когда программа, отвечающая за взаимодействие с базой данных, считывала несколько строк моего запроса как одну гигантскую строку. Это означало, что строковый комментарий испортил оставшуюся часть запроса. Исправление заключалось в использовании вместо этого / * блочного комментария * /.
person
calamari
schedule
07.04.2020
Problem Description:
I have used the next SQL statement in both MySQL and PostgreSQL, but it fails in PostgreSQL
db.Query(`SELECT COUNT(*) as N FROM email WHERE address = ?`, email)
with this error:
pq: F:"scan.l" M:"syntax error at end of input" S:"ERROR" C:"42601" P:"50" R:"scanner_yyerror" L:"993"
What’s the problem? The error messages in PostgreSQL are very cryptic.
Solution – 1
You are using Go right?
try:
db.Query(`SELECT COUNT(*) as N FROM email WHERE address = $1`, email)
Solution – 2
You haven’t provided any details about the language/environment, but I’ll try a wild guess anyway:
MySQL’s prepared statements natively use ?
as the parameter placeholder, but PostgreSQL uses $1
, $2
etc. Try replacing the ?
with $1
and see if it works:
WHERE address = $1
The error messages in PostgreSQL are very cryptic.
In general, I’ve found that Postgres error messages are better than competing products (ahem, MySQL and especially Oracle), but in this instance you’ve managed to confuse the parser beyond sanity. 🙂
Solution – 3
In golang for queries we have use
- MySQL uses the ? variant
- PostgreSQL uses an enumerated $1, $2, etc bindvar syntax
- SQLite accepts both ? and $1 syntax
- Oracle uses a :name syntax
Solution – 4
In my case, it was due to using a — line comment where the program that was responsible for interacting with the database read in the multiple lines of my query all as one giant line. This meant that the line comment corrupted the remainder of the query. The fix was to use a /* block comment */ instead.
I am getting an error in my PostGresQL code.
org.postgresql.util.PSQLException: ERROR: syntax error at end of input
Position: 250
FROM
tutorial.crunchbase_companies
This usually works so I am not sure what my error means.
asked Mar 3, 2021 at 15:50
4
I suspect that you want the total companies, the companies with non-NULL values for a column and the ratio.
If so, this has nothing to do with distinct
:
SELECT COUNT(*),
COUNT(funding_total_usd) as num_with_funding,
AVG( (funding_total_usd IS NOT NULL)::int ) as ratio_with_funding
FROM tutorial.crunchbase_companies;
answered Mar 3, 2021 at 15:54
Gordon LinoffGordon Linoff
1.2m57 gold badges640 silver badges782 bronze badges