I have a postgresql db with a number of tables. If I query:
SELECT column_name
FROM information_schema.columns
WHERE table_name="my_table";
I will get a list of the columns returned properly.
However, when I query:
SELECT *
FROM "my_table";
I get the error:
(ProgrammingError) relation "my_table" does not exist
'SELECT *n FROM "my_table"n' {}
Any thoughts on why I can get the columns, but can’t query the table? Goal is to be able to query the table.
asked Apr 20, 2016 at 19:38
patkilpatkil
1,8493 gold badges15 silver badges17 bronze badges
3
You have to include the schema if isnt a public one
SELECT *
FROM <schema>."my_table"
Or you can change your default schema
SHOW search_path;
SET search_path TO my_schema;
Check your table schema here
SELECT *
FROM information_schema.columns

For example if a table is on the default schema public both this will works ok
SELECT * FROM parroquias_region
SELECT * FROM public.parroquias_region
But sectors need specify the schema
SELECT * FROM map_update.sectores_point
answered Apr 20, 2016 at 19:44
6
You can try:
SELECT *
FROM public."my_table"
Don’t forget double quotes near my_table.
![]()
4b0
21.4k30 gold badges95 silver badges139 bronze badges
answered Sep 3, 2019 at 2:13
2
I had to include double quotes with the table name.
db=> d
List of relations
Schema | Name | Type | Owner
--------+-----------------------------------------------+-------+-------
public | COMMONDATA_NWCG_AGENCIES | table | dan
...
db=> d COMMONDATA_NWCG_AGENCIES
Did not find any relation named "COMMONDATA_NWCG_AGENCIES".
???
Double quotes:
db=> d "COMMONDATA_NWCG_AGENCIES"
Table "public.COMMONDATA_NWCG_AGENCIES"
Column | Type | Collation | Nullable | Default
--------------------------+-----------------------------+-----------+----------+---------
ID | integer | | not null |
...
Lots and lots of double quotes:
db=> select ID from COMMONDATA_NWCG_AGENCIES limit 1;
ERROR: relation "commondata_nwcg_agencies" does not exist
LINE 1: select ID from COMMONDATA_NWCG_AGENCIES limit 1;
^
db=> select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
ERROR: column "id" does not exist
LINE 1: select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
^
db=> select "ID" from "COMMONDATA_NWCG_AGENCIES" limit 1;
ID
----
1
(1 row)
This is postgres 11. The CREATE TABLE statements from this dump had double quotes as well:
DROP TABLE IF EXISTS "COMMONDATA_NWCG_AGENCIES";
CREATE TABLE "COMMONDATA_NWCG_AGENCIES" (
...
answered Sep 26, 2019 at 21:57
dfrankowdfrankow
19.5k40 gold badges144 silver badges203 bronze badges
1
I hit this error and it turned out my connection string was pointing to another database, obviously the table didn’t exist there.
I spent a few hours on this and no one else has mentioned to double check your connection string.
answered Nov 13, 2020 at 2:29
![]()
Jeremy ThompsonJeremy Thompson
59.7k32 gold badges183 silver badges308 bronze badges
2
I had the same problem that occurred after I restored data from a postgres dumped db.
My dump file had the command below from where things started going south.
SELECT pg_catalog.set_config('search_path', '', false);
Solutions:
- Probably remove it or change that
falseto betrue. - Create a private schema that will be used to access all the tables.
The command above simply deactivates all the publicly accessible schemas.
Check more on the documentation here: https://www.postgresql.org/docs/9.3/ecpg-connect.html
answered Sep 17, 2019 at 16:51
![]()
dmigwidmigwi
611 silver badge5 bronze badges
0
The error can be caused by access restrictions. Solution:
GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;
answered Oct 1, 2020 at 0:47
MarcelMarcel
2,7102 gold badges25 silver badges43 bronze badges
I was using pgAdmin to create my tables and while I was not using reserved words, the generated table had a quote in the name and a couple of columns had quotes in them. Here is an example of the generated SQL.
CREATE TABLE public."Test"
(
id serial NOT NULL,
data text NOT NULL,
updater character varying(50) NOT NULL,
"updateDt" time with time zone NOT NULL,
CONSTRAINT test_pk PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE public."Test"
OWNER to svc_newnews_app;
All of these quotes were inserted at «random». I just needed to drop and re-create the table again without the quotes.
Tested on pgAdmin 4.26
answered Oct 9, 2020 at 14:05
![]()
ChewyChewy
6526 silver badges21 bronze badges
Please ensure that:
- Your password is non-empty
- In case it is empty, do not pass the
passwordparam in the connection string
This is one of the most common errors when starting out with the tutorial.
answered Mar 6, 2022 at 8:21
![]()
In my case, the dump file I restored had these commands.
CREATE SCHEMA employees;
SET search_path = employees, pg_catalog;
I’ve commented those and restored again. The issue got resolved
answered Oct 30, 2020 at 12:03
samsrisamsri
1,07412 silver badges23 bronze badges
Keep all your table names in lower case because when you rollback and then go to latest, it’s looking for lowercase apparently.
answered Oct 25, 2021 at 8:00
ErickErick
211 silver badge3 bronze badges
Lets say we have database name as students and schema name as studentinformation then to use all the table of this schema we need to set the path first which we can do in postgresql like:
client.connect()
.then(()=>console.log("connected succesfully"))
.then(()=>client.query("set search_path to students"))
.then(()=>client.query("show search_path"))
.then(()=>client.query("set search_path to studentinformation"))
.then(()=>client.query("show search_path"))
.then(results => console.table(results.rows)) //setting the search path
![]()
Toni
1,5214 gold badges15 silver badges23 bronze badges
answered Jul 1, 2021 at 17:36
What you had originally was a correct syntax — for tables, not for schemas. As you did not have a table (dubbed ‘relation’ in the error message), it threw the not-found error.
I see you’ve already noticed this — I believe there is no better way of learning than to fix our own mistakes 😉
But there is something more. What you are doing above is too much on one hand, and not enough on the other.
Running the script, you
- create a schema
- create a role
- grant
SELECTon all tables in the schema created in (1.) to this new role_ - and, finally, grant all privileges (
CREATEandUSAGE) on the new schema to the new role
The problem lies within point (3.) You granted privileges on tables in replays — but there are no tables in there! There might be some in the future, but at this point the schema is completely empty. This way, the GRANT in (3.) does nothing — this way you are doing too much.
But what about the future tables?
There is a command for covering them: ALTER DEFAULT PRIVILEGES. It applies not only to tables, but:
Currently [as of 9.4], only the privileges for tables (including views and foreign tables), sequences, functions, and types (including domains) can be altered.
There is one important limitation, too:
You can change default privileges only for objects that will be created by yourself or by roles that you are a member of.
This means that a table created by alice, who is neither you nor a role than you are a member of (can be checked, for example, by using du in psql), will not take the prescribed access rights. The optional FOR ROLE clause is used for specifying the ‘table creator’ role you are a member of. In many cases, this implies it is a good idea to create all database objects using the same role — like mydatabase_owner.
A small example to show this at work:
CREATE ROLE test_owner; -- cannot log in
CREATE SCHEMA replays AUTHORIZATION test_owner;
GRANT ALL ON SCHEMA replays TO test_owner;
SET ROLE TO test_owner; -- here we change the context,
-- so that the next statement is issued as the owner role
ALTER DEFAULT PRIVILEGES IN SCHEMA replays GRANT SELECT ON TABLES TO alice;
CREATE TABLE replays.replayer (r_id serial PRIMARY KEY);
RESET ROLE; -- changing the context back to the original role
CREATE TABLE replays.replay_event (re_id serial PRIMARY KEY);
-- and now compare the two
dp replays.replayer
Access privileges
Schema │ Name │ Type │ Access privileges │ Column access privileges
─────────┼──────────┼───────┼───────────────────────────────┼──────────────────────────
replays │ replayer │ table │ alice=r/test_owner ↵│
│ │ │ test_owner=arwdDxt/test_owner │
dp replays.replay_event
Access privileges
Schema │ Name │ Type │ Access privileges │ Column access privileges
─────────┼──────────────┼───────┼───────────────────┼──────────────────────────
replays │ replay_event │ table │ │
As you can see, alice has no explicit rights on the latter table. (In this case, she can still SELECT from the table, being a member of the public pseudorole, but I didn’t want to clutter the example by revoking the rights from public.)
What you had originally was a correct syntax — for tables, not for schemas. As you did not have a table (dubbed ‘relation’ in the error message), it threw the not-found error.
I see you’ve already noticed this — I believe there is no better way of learning than to fix our own mistakes 😉
But there is something more. What you are doing above is too much on one hand, and not enough on the other.
Running the script, you
- create a schema
- create a role
- grant
SELECTon all tables in the schema created in (1.) to this new role_ - and, finally, grant all privileges (
CREATEandUSAGE) on the new schema to the new role
The problem lies within point (3.) You granted privileges on tables in replays — but there are no tables in there! There might be some in the future, but at this point the schema is completely empty. This way, the GRANT in (3.) does nothing — this way you are doing too much.
But what about the future tables?
There is a command for covering them: ALTER DEFAULT PRIVILEGES. It applies not only to tables, but:
Currently [as of 9.4], only the privileges for tables (including views and foreign tables), sequences, functions, and types (including domains) can be altered.
There is one important limitation, too:
You can change default privileges only for objects that will be created by yourself or by roles that you are a member of.
This means that a table created by alice, who is neither you nor a role than you are a member of (can be checked, for example, by using du in psql), will not take the prescribed access rights. The optional FOR ROLE clause is used for specifying the ‘table creator’ role you are a member of. In many cases, this implies it is a good idea to create all database objects using the same role — like mydatabase_owner.
A small example to show this at work:
CREATE ROLE test_owner; -- cannot log in
CREATE SCHEMA replays AUTHORIZATION test_owner;
GRANT ALL ON SCHEMA replays TO test_owner;
SET ROLE TO test_owner; -- here we change the context,
-- so that the next statement is issued as the owner role
ALTER DEFAULT PRIVILEGES IN SCHEMA replays GRANT SELECT ON TABLES TO alice;
CREATE TABLE replays.replayer (r_id serial PRIMARY KEY);
RESET ROLE; -- changing the context back to the original role
CREATE TABLE replays.replay_event (re_id serial PRIMARY KEY);
-- and now compare the two
dp replays.replayer
Access privileges
Schema │ Name │ Type │ Access privileges │ Column access privileges
─────────┼──────────┼───────┼───────────────────────────────┼──────────────────────────
replays │ replayer │ table │ alice=r/test_owner ↵│
│ │ │ test_owner=arwdDxt/test_owner │
dp replays.replay_event
Access privileges
Schema │ Name │ Type │ Access privileges │ Column access privileges
─────────┼──────────────┼───────┼───────────────────┼──────────────────────────
replays │ replay_event │ table │ │
As you can see, alice has no explicit rights on the latter table. (In this case, she can still SELECT from the table, being a member of the public pseudorole, but I didn’t want to clutter the example by revoking the rights from public.)
Содержание
- Debugging “relation does not exist” error in postgres
- Нельзя просто использовать имя таблицы PostgreSQL («отношение не существует»)
- 7 ответов:
- Нельзя просто использовать имя таблицы PostgreSQL («отношения не существует»)
- org.postgresql.util.PSQLException: ОШИБКА: отношение «app_user» не существует
- 3 ответа
- Java SQL «ОШИБКА: отношение» Имя_таблицы «не существует»
- 4 ответы
Debugging “relation does not exist” error in postgres
So, i was getting this nasty error even when the table clearly existed in t11 database.
Even after lot of googling, debugging and trying Stackoverflow solutions, there was no resolution. Then i got a hunch, that i should check what database and schema were actually being used when done programmatically (even though dbname was clearly provided in connection string).
If you use database t11 by running c t11 and then run:
select * from information_schema.tables where table_schema NOT IN (‘pg_catalog’, ‘information_schema’)
It will tell you that userinfo5 does exist in t11 database. But what happens when we try to access it programmatically?
So, i ran above query in a golang function, the function which was earlier running query select * from userinfo5 where >
Output showed that database name which was actually being used was postgres and not t11 Why?
Because, my postgres user was configured to not use password. But my connection string had password= This was somehow confusing the DB driver and postgres database was being used and not t11 .
remove password= from connection string so that it looks like: “host=localhost port=5432 user=postgres dbname=t11 sslmode=disable”
- Alter user postgres so that it uses password: alter user postgres with password ‘pwd123’;
- Change connection string: “host=localhost port=5432 user=postgres password=pwd123 dbname=t11 sslmode=disable”
Источник
Нельзя просто использовать имя таблицы PostgreSQL («отношение не существует»)
Я пытаюсь запустить следующий PHP-скрипт для выполнения простого запроса к базе данных:
это приводит к следующей ошибке:
ошибка запроса: ошибка: отношение «sf_bands» не существует
во всех примерах я могу найти, где кто-то получает ошибку о том, что связь не существует, это потому, что они используют прописные буквы в имени своей таблицы. Мое имя таблицы не имеет прописных букв. Есть ли способ запросить мою таблицу без включения имени базы данных, т. е. showfinder.sf_bands ?
7 ответов:
из того, что я прочитал, эта ошибка означает, что вы не ссылаетесь на имя таблицы правильно. Одна из распространенных причин заключается в том, что таблица определяется со смешанным написанием, и вы пытаетесь запросить ее со всеми строчными буквами.
другими словами, следующее терпит неудачу:
используйте двойные кавычки для разграничения идентификаторов, чтобы вы могли использовать конкретное смешанное написание, как определено в таблице.
Re ваш комментарий, вы можете добавить схему в «search_path», чтобы при ссылке на имя таблицы без уточнения ее схемы запрос соответствовал этому имени таблицы, проверяя каждую схему по порядку. Так же, как PATH в оболочке или include_path в PHP и др. Вы можете проверить свой текущий путь поиска схема:
вы можете изменить путь поиска схемы:
у меня были проблемы с этим и это история (печальная, но правдивая) :
если ваше имя таблицы все строчные, как: счета вы можете использовать: select * from AcCounTs и он будет работать нормально
если ваше имя таблицы все строчные, как: accounts Следующее не удастся: select * from «AcCounTs»
если ваше имя таблицы смешанный случай как: Accounts Следующее не удастся: select * from accounts
если ваше имя таблицы это смешанный случай как : Accounts Следующее будет работать нормально: select * from «Accounts»
Я не люблю вспоминать бесполезные вещи, как это, но надо 😉
запрос процесса Postgres отличается от других RDMS. Поместите имя схемы в двойную кавычку перед именем таблицы, например, «SCHEMA_NAME».»SF_Bands»
поместите параметр dbname в строку подключения. Это работает для меня, в то время как все остальное не удалось.
также, когда делаешь выбор, указать your_schema . your_table такой:
У меня была аналогичная проблема на OSX, но я пытался играть с двойными и одинарными кавычками. Для вашего случая, вы могли бы попробовать что-то вроде этого
для меня проблема заключалась в том, что я использовал запрос к этой конкретной таблице во время инициализации Django. Конечно, это вызовет ошибку, потому что эти таблицы не существовали. В моем случае это было get_or_create метод в пределах a admin.py файл, который выполнялся всякий раз, когда программное обеспечение выполняло какую-либо операцию (в данном случае миграцию). Надеюсь, это кому-то поможет.
я копал эту проблему больше, и узнал о том, как установить этот «search_path» по defoult для нового пользователя в текущей базе данных.
открыть Свойства базы данных, затем открыть лист » переменные» и просто добавьте эту переменную для вашего пользователя с фактическим значением.
Так что теперь ваш пользователь получит это schema_name по умолчанию, и вы можете использовать tableName без schemaName.
Источник
Нельзя просто использовать имя таблицы PostgreSQL («отношения не существует»)
Я пытаюсь запустить следующий скрипт PHP, чтобы выполнить простой запрос к базе данных:
Это приводит к следующей ошибке:
Ошибка запроса: ERROR: отношения «sf_bands» не существует
Во всех примерах я могу найти, где кто-то получает ошибку, указывающую, что отношения не существует, потому что они используют заглавные буквы в имени своей таблицы. В моем имени таблицы нет заглавных букв. Есть ли способ запросить мою таблицу без включения имени базы данных, то есть showfinder.sf_bands ?
Из того, что я прочитал, эта ошибка означает, что вы неправильно ссылаетесь на имя таблицы. Одной из распространенных причин является то, что таблица определена с орфографией с смешанным регистром, и вы пытаетесь запросить ее со всеми строчными буквами.
Другими словами, следующее не выполняется:
Используйте двойные кавычки, чтобы разграничить идентификаторы, чтобы вы могли использовать конкретную орфографию с смешанным регистром, поскольку таблица определена.
Повторите свой комментарий, вы можете добавить схему в «путь поиска», чтобы при ссылке на имя таблицы без квалификации ее схемы запрос соответствовал этому имени таблицы, проверив каждую схему в порядке. Точно так же, как PATH в оболочке или include_path в PHP и т. Д. Вы можете проверить свой текущий путь поиска схемы:
Вы можете изменить путь поиска схемы:
У меня были проблемы с этим, и это история (грустная, но правда):
Если имя вашей таблицы имеет нижний регистр, например: учетные записи, которые вы можете использовать: select * from AcCounTs и он будет работать нормально
Если ваше имя таблицы имеет все нижеследующее значение, например: accounts Следующие select * from «AcCounTs» не будут выполнены: select * from «AcCounTs»
Если ваше имя таблицы смешанно, например: Accounts : Accounts : select * from accounts
Если ваше имя таблицы смешанно, например: Accounts Следующие будут работать нормально: select * from «Accounts»
Я не люблю вспоминать бесполезные вещи, как это, но вы должны;)
Запрос процесса Postgres отличается от других RDMS. Поместите имя схемы в двойную кавычку перед именем вашей таблицы, например «SCHEMA_NAME». «SF_Bands»
Поместите параметр dbname в строку подключения. Это работает для меня, пока все остальное не удалось.
Также, когда вы делаете выбор, укажите your_schema . your_table :
У меня была аналогичная проблема с OSX, но я старался играть с двойными и одинарными кавычками. В вашем случае вы можете попробовать что-то вроде этого
Источник
org.postgresql.util.PSQLException: ОШИБКА: отношение «app_user» не существует
У меня есть приложение, в котором я использую spring boot и postgres. Я получаю эту ошибку, когда пытаюсь создать пользователя.
Когда я запускаю этот запрос в своей базе данных, я получаю ту же ошибку:
Но если я изменил это на:
Как мне настроить это приложение для загрузки spring?
зависимости в pom.xml:
Я вызываю это действие из формы:
и это мой контроллер:
Валидатор, который исправляет ошибку:
И репозиторий является интерфейсом CrudRepository и не имеет реализации:
И отлаживая валидатор, я мог бы получить этот стек:
Спасибо за помощь!
3 ответа
PostgreSQL соответствует стандарту SQL и в этом случае означает, что идентификаторы (имена таблиц, имена столбцов и т.д.) принудительно строятся в нижнем регистре, за исключением случаев, когда они цитируются. Поэтому, когда вы создаете таблицу следующим образом:
вы фактически получаете таблицу app_user . Вы, очевидно, сделали:
а затем вы получите таблицу «APP_USER» .
В Spring вы указываете правильную строку для имени таблицы заглавными буквами, но ее объединяют в запрос на сервер PostgreSQL без кавычек. Вы можете проверить это, прочитав файлы журнала PostgreSQL: он должен показать запрос, сгенерированный Spring, за которым следует ошибка в верхней части вашего сообщения.
Поскольку у вас очень мало контроля над тем, как Spring строит запросы от сущностей, вам лучше использовать идентификаторы нижнего регистра стандарта SQL.
Источник
Java SQL «ОШИБКА: отношение» Имя_таблицы «не существует»
Я пытаюсь подключить netbeans к моей базе данных postgresql. Кажется, что соединение сработало, поскольку я не получаю никаких ошибок или исключений при простом подключении, такие методы, как getCatalog (), также возвращают правильные ответы.
Но когда я пытаюсь запустить простой оператор SQL, я получаю сообщение об ошибке «ОШИБКА: отношение« TABLE_NAME »не существует», где TABLE_NAME — это любая из моих таблиц, которые ДЕЙСТВИТЕЛЬНО существуют в базе данных. Вот мой код:
Я думал, что netbeans может не находить таблицы, потому что он не ищет схему по умолчанию (общедоступную), есть ли способ установить схему в java?
РЕДАКТИРОВАТЬ: мой код подключения. Имя базы данных — Cinemax, когда я опускаю код оператора, я не получаю ошибок.
Разве нельзя так переписать sql? SELECT * FROM .clients — CoolBeans
Вы не показываете, как вы подключаетесь к серверу базы данных. Я подозреваю, что @CoolBeans верен выше или очень близко. Ваша таблица находится в другой схеме (что будет исправлено выше) или в другой базе данных, чем та, которую вы указали при подключении. — Brian Roach
Мне это нравится . не могли бы вы показать нам НАСТОЯЩУЮ ошибку? Я не думаю, что база данных говорит «отношение TABLE_NAME . », когда вы выполняете «select * from clients». — Szymon Lipiński
Я пробовал это, но получаю ту же ошибку: «ОШИБКА: отношение« public.clients »не существует» (то же самое для любой другой из моих таблиц). public — моя единственная схема, так что это также схема по умолчанию. Спасибо за помощь. — Matt
Установите для log_min_duration_statement значение 0 в postgresql.conf, перезапустите базу данных, запустите приложение и проверьте в журналах postgresql, какой реальный запрос отправляется в базу данных. И еще кое-что . вы на 100% уверены, что у вас есть стол? Можете ли вы подключиться к этой базе данных с помощью psql / pgadmin и выполнить там запрос? — Szymon Lipiński
4 ответы
Я подозреваю, что вы создали таблицу, используя двойные кавычки, например, «Clients» или какая-либо другая комбинация символов верхнего / нижнего регистра, поэтому имя таблицы теперь чувствительно к регистру.
Что означает заявление
Если возвращаемое имя таблицы не в нижнем регистре, вы должны использовать двойные кавычки при обращении к нему, что-то вроде этого:
ответ дан 24 апр.
Я пытаюсь использовать sequelize ORM, и в своем запросе на создание он использует кавычки в table_name. Спасибо за ответ. — Kiddo
Источник
I used pg_restore to load my postgres db with a dump file.
I connected to my db with my user :
sudo -u arajguru psql dump
select current_user;
current_user
--------------
arajguru
Now I was able to see all the newly created tables:
dump=> dt
List of relations
Schema | Name | Type | Owner
--------+-------------------+-------+----------
public | Approvals | table | arajguru
public | Approvers | table | arajguru
public | Conditions | table | arajguru
public | Entities | table | arajguru
public | EntityDefinitions | table | arajguru
public | Projects | table | arajguru
public | Rules | table | arajguru
public | run_history | table | arajguru
(8 rows)
But when I try to fire a select * query, it gave me this error:
dump=> select * from Approvals;
ERROR: relation "approvals" does not exist
LINE 1: select * from Approvals;
What can be the reason for this error? Please help.
Содержание
- Debugging “relation does not exist” error in postgres
- PostgreSQL relation «mytable» does not exist #1044
- Comments
- sergioszy commented Dec 16, 2017
- Environment
- brettwooldridge commented Dec 16, 2017
- sergioszy commented Dec 16, 2017
- org.postgresql.util.PSQLException:ERROR: relation «contacts» does not exist
- Comments
Debugging “relation does not exist” error in postgres
So, i was getting this nasty error even when the table clearly existed in t11 database.
Even after lot of googling, debugging and trying Stackoverflow solutions, there was no resolution. Then i got a hunch, that i should check what database and schema were actually being used when done programmatically (even though dbname was clearly provided in connection string).
If you use database t11 by running c t11 and then run:
select * from information_schema.tables where table_schema NOT IN (‘pg_catalog’, ‘information_schema’)
It will tell you that userinfo5 does exist in t11 database. But what happens when we try to access it programmatically?
So, i ran above query in a golang function, the function which was earlier running query select * from userinfo5 where >
Output showed that database name which was actually being used was postgres and not t11 Why?
Because, my postgres user was configured to not use password. But my connection string had password= This was somehow confusing the DB driver and postgres database was being used and not t11 .
remove password= from connection string so that it looks like: “host=localhost port=5432 user=postgres dbname=t11 sslmode=disable”
- Alter user postgres so that it uses password: alter user postgres with password ‘pwd123’;
- Change connection string: “host=localhost port=5432 user=postgres password=pwd123 dbname=t11 sslmode=disable”
Источник
PostgreSQL relation «mytable» does not exist #1044
Environment
PreparedStatement prepared = connection.preparedStatement(
«select mytable.column1, mytable.column2 from mytable where mytable.column1 > 0» ); //OK
When execute resultSet = prepared.executeQuery();
throws this exception
org.postgresql.util.PSQLException: ERROR: relation mytable does not exist
Position: 176
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2190)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:169)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:117)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
The text was updated successfully, but these errors were encountered:
This is not a HikariCP question, this is a PostgreSQL question.
PostgreSQL will not throw an error on prepare, even if the relation does not exist, because the driver will not actually prepare the statement until it has been executed several times. Creating a Statement via Statement stmt = connection.createStatement() , and then executing the same query via resultSet = stmt.executeQuery(«select . «) will fail with the same error.
You may be connecting to PostgreSQL server, but you are not connecting to the database which contains that table. Either specifiy the database, or check that the user has permission to see that table.
But, if I use directly the PGSimpleDatasource everthing is OK. Then the problem is in how HikariCP
Источник
org.postgresql.util.PSQLException:ERROR: relation «contacts» does not exist
Hello, I am pretty new to java and NetBeans. I am getting an error that appears when NetBeans tries to insert a record into a PostgreSQL database. I am using the files that are from a Sun Java tutorial.
————————————-
insert into contacts(id, first_name, last_name)
org.postgresql.util.PSQLException: ERROR: relation «contacts» does not exist
————————————-
I think PostgreSQL needs a SQL statement to formatted like the following: «schema».»tablename»
To include parenthesis around the schema name followed by a dot, followed by the table name. But in the insert statement that NetBeans is creating, just includes the the table name. I have tried to modify the code in different ways, but I can’t get it to format the SQL statement correctly.
I have included the entire statement below. Thanks again for any help.
/**
* Updates the selected contact or inserts a new one (if we are
* in the insert mode).
*
* @param firstName first name of the contact.
* @param lastName last name of the contact.
* @param title title of the contact.
* @param nickname nickname of the contact.
* @param displayFormat display format for the contact.
* @param mailFormat mail format for the contact.
* @param emails email addresses of the contact.
*/
public void updateContact(String firstName, String lastName, String title, String nickname,
int displayFormat, int mailFormat, Object[] emails) <
int selection = getContactSelection().getMinSelectionIndex();
Statement stmt = null;
try <
if (!insertMode) <
rowSet.absolute(selection+1);
>
Connection con = rowSet.getConnection();
stmt = con.createStatement();
String sql;
if (insertMode) <
sql = «insert into public.» + CONTACTS_TABLE + «(» + CONTACTS_KEY + «, » + CONTACTS_FIRST_NAME + «, »
+ CONTACTS_LAST_NAME + «, » + CONTACTS_TITLE + «, » + CONTACTS_NICKNAME + «, »
+ CONTACTS_DISPLAY_FORMAT + «, » + CONTACTS_MAIL_FORMAT + «, » + CONTACTS_EMAIL_ADDRESSES
+ «) values ((case when (select max(» + CONTACTS_KEY + «) from » + CONTACTS_TABLE + «)»
+ «IS NULL then 1 else (select max(» + CONTACTS_KEY + «) from » + CONTACTS_TABLE + «)+1 end), »
+ encodeSQL(firstName) + «, » + encodeSQL(lastName) + «, » + encodeSQL(title) + «, »
+ encodeSQL(nickname) + «, » + displayFormat + «, » + mailFormat + «, »
+ encodeSQL(encodeEmails(emails)) + «)»;
> else <
sql = «update public.» + CONTACTS_TABLE + » set «;
sql += CONTACTS_FIRST_NAME + ‘=’ + encodeSQL(firstName) + «, «;
sql += CONTACTS_LAST_NAME + ‘=’ + encodeSQL(lastName) + «, «;
sql += CONTACTS_TITLE + ‘=’ + encodeSQL(title) + «, «;
sql += CONTACTS_NICKNAME + ‘=’ + encodeSQL(nickname) + «, «;
sql += CONTACTS_DISPLAY_FORMAT + ‘=’ + displayFormat + «, «;
sql += CONTACTS_MAIL_FORMAT + ‘=’ + mailFormat + «, «;
sql += CONTACTS_EMAIL_ADDRESSES + ‘=’ + encodeSQL(encodeEmails(emails));
sql += » where » + CONTACTS_KEY + ‘=’ + rowSet.getObject(CONTACTS_KEY);
>
System.out.println(sql);
stmt.executeUpdate(sql);
rowSet.execute();
> catch (SQLException sqlex) <
sqlex.printStackTrace();
> finally <
setInsertMode(false);
if (stmt != null) <
try <
stmt.close();
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
>
>
>
What’s that «encodeSQL» method doing? You’re much better off with a PreparedStatement, IMO.
No, you don’t need the «public.». Connect to the database and use the table name just as it appears in the Postgres client. That’s what I do. It works fine.
That’s the worst way you can possible build up that SQL statement. Why create all those extra Strings? Better to use a StringBuffer and PreparedStatement.
No transactional logic that I can see. Wouldn’t you want the INSERT to rollback if an exception is caught?
The writeable row set must be a data member of this class. You’ve done nothing to synchronize this method, so it’s not thread safe. Don’t use it with more than one client.
Thanks for your reply.
Knowing that I don’t need the «public» schema keyword helps, but I think I still need the » » double quotes around the table name?
Below is the entire code. Does this look thread safe or like it has any transaction logic?
import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeListener;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
/**
* Model of Contacts application.
*
* @author Jan Stola
*/
public class ContactsModel implements ListSelectionListener <
// Constants for database objects
private static final String CONTACTS_TABLE = «contacts»;
private static final String CONTACTS_KEY = «id»;
private static final String CONTACTS_ID = «id»;
private static final String CONTACTS_FIRST_NAME = «first_name»;
private static final String CONTACTS_LAST_NAME = «last_name»;
private static final String CONTACTS_TITLE = «title»;
private static final String CONTACTS_NICKNAME = «nickname»;
private static final String CONTACTS_DISPLAY_FORMAT = «display_format»;
private static final String CONTACTS_MAIL_FORMAT = «mail_format»;
private static final String CONTACTS_EMAIL_ADDRESSES = «email_addresses»;
// Constants for property names
public static final String PROP_REMOVAL_ENABLED = «removalEnabled»;
public static final String PROP_EDITING_ENABLED = «editingEnabled»;
// RowSet with contacts
private JDBCRowSet rowSet;
// Contacts selection model
private ListSelectionModel contactSelection;
// Insert mode (e.g. are we about to insert a new contact)
private boolean insertMode;
/**
* Getter for rowSet property.
*
* @return rowSet with contacts.
*/
public JDBCRowSet getRowSet() <
return rowSet;
>
/**
* Setter for rowSet property.
*
* @param rowSet rowSet with contacts.
*/
public void setRowSet(JDBCRowSet rowSet) <
this.rowSet = rowSet;
>
/**
* Getter for contactSelection property.
*
* @return contacts selection model.
*/
public ListSelectionModel getContactSelection() <
if (contactSelection == null) <
contactSelection = new DefaultListSelectionModel();
contactSelection.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setContactSelection(contactSelection);
>
return contactSelection;
>
/**
* Setter for contactSelection property.
*
* @param contactSelection contacts selection model.
*/
public void setContactSelection(ListSelectionModel contactSelection) <
if (this.contactSelection != null) <
this.contactSelection.removeListSelectionListener(this);
>
this.contactSelection = contactSelection;
contactSelection.addListSelectionListener(this);
>
/**
* Setter for insertMode property.
*
* @param insertMode insert mode.
*/
void setInsertMode(boolean insertMode) <
this.insertMode = insertMode;
>
/**
* Returns ID of the selected contact.
*
* @return ID of the selected contact.
*/
public String getID() <
return insertMode ? null : stringValue(CONTACTS_ID);
>
/**
* Returns the first name of the selected contact.
*
* @return the first name of the selected contact.
*/
public String getFirstName() <
return insertMode ? «» : stringValue(CONTACTS_FIRST_NAME);
>
/**
* Returns the last name of the selected contact.
*
* @return the last name of the selected contact.
*/
public String getLastName() <
return insertMode ? «» : stringValue(CONTACTS_LAST_NAME);
>
/**
* Returns title of the selected contact.
*
* @return title of the selected contact.
*/
public String getTitle() <
return insertMode ? «» : stringValue(CONTACTS_TITLE);
>
/**
* Returns nickname of the selected contact.
*
* @return nickname of the selected contact.
*/
public String getNickname() <
return insertMode ? «» : stringValue(CONTACTS_NICKNAME);
>
/**
* Returns display format of the selected contact.
*
* @return display format of the selected contact.
*/
public int getDisplayFormat() <
return insertMode ? 0 : intValue(CONTACTS_DISPLAY_FORMAT);
>
/**
* Returns mail format of the selected contact.
*
* @return mail format of the selected contact.
*/
public int getMailFormat() <
return insertMode ? 0 : intValue(CONTACTS_MAIL_FORMAT);
>
/**
* Returns email addresses of the selected contact.
*
* @return email addresses of the selected contact.
*/
public Object[] getEmails() <
String encodedEmails = insertMode ? null : stringValue(CONTACTS_EMAIL_ADDRESSES);
return decodeEmails(encodedEmails);
>
/**
* Determines whether editing of the selected contact is enabled.
*
* @return true if the selected contact can be edited,
* returns false otherwise.
*/
public boolean isEditingEnabled() <
// Additional business logic can go here
return (getContactSelection().getMinSelectionIndex() != -1);
>
/**
* Determines whether removal of the selected contact is enabled.
*
* @return true if the selected contact can be removed,
* returns false otherwise.
*/
public boolean isRemovalEnabled() <
// Additional business logic can go here
return (getContactSelection().getMinSelectionIndex() != -1);
>
// Helper method that returns value of a selected contact’s attribute
private String stringValue(String columnName) <
String value = null;
try <
if ((rowSet != null) && selectContactInRowSet()) <
value = rowSet.getString(columnName);
>
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
return value;
>
// Helper method that returns value of a selected contact’s attribute
private int intValue(String columnName) <
int value = 0;
try <
if ((rowSet != null) && selectContactInRowSet()) <
value = rowSet.getInt(columnName);
>
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
return value;
>
// Helper method that synchronizes rowSet position with selected contact
private boolean selectContactInRowSet() <
int index = getContactSelection().getMinSelectionIndex();
if (index != -1) <
try <
rowSet.absolute(index+1);
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
>
return (index != -1);
>
// Helper method that decodes email addresses from the encoded string
private Object[] decodeEmails(String encodedEmails) <
if ((encodedEmails == null) || (encodedEmails.equals(«»))) <
return new String[0];
>
char sep = encodedEmails.charAt(0);
List emails = new LinkedList();
StringTokenizer st = new StringTokenizer(encodedEmails, String.valueOf(sep));
while (st.hasMoreTokens()) <
emails.add(st.nextToken());
>
return emails.toArray(new Object[emails.size()]);
>
// Helper method that encodes email addresses into one string
private String encodeEmails(Object[] emails) <
StringBuffer sb = new StringBuffer();
for (int i=0; i 0 · Share on Twitter Share on Facebook
Источник
I am trying to run hibernate on a PostgreSQL 8.4.2 DB. Whenever I try to run a simple java code like:
List<User> users = service.findAllUsers();
I get the following error:
PSQLException: ERROR: relation "TABLE_NAME" does not exist
Since I have option hibernate.show_sql option set to true, I can see that hibernate is trying to run the following SQL command:
select this_.USERNAME as USERNAME0_0_, this_.PASSWORD as PASSWORD0_0_
from "TABLE_NAME" this_
When in reality, it should at least run something like:
select this_."USERNAME" as USERNAME0_0_, this_."PASSWORD" as PASSWORD0_0_
from "SCHEMA_NAME"."TABLE_NAME" as this_
Does anyone know what changes I need to make for Hibernate to produce the right SQL for PostgreSQL?
I have set up the necessary postgreSQL datasource in applicationContext.xml file:
<!-- Use Spring annotations -->
<context:annotation-config />
<!-- postgreSQL datasource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url"
value="jdbc:postgresql://localhost/DB_NAME:5432/SCHEMA_NAME" />
<property name="username" value="postgres" />
<property name="password" value="password" />
<property name="defaultAutoCommit" value="false" />
</bean>
On the same file I have set up the session factory with PostgreSQL dialect:
<!-- Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.myPackage.dbEntities.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- setup transaction manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
Finally, the way I am mapping the domain class to the table is:
@Entity
@Table(name = "`TABLE_NAME`")
public class User {
@Id
@Column(name = "USERNAME")
private String username;
Has anyone encountered a similar error?. Any help in solving this issue will be much appreciated.
Please note that question is different to post Cannot simply use PostgreSQL table name (”relation does not exist”)
Apologies for the lengthy post.
I am trying to run hibernate on a PostgreSQL 8.4.2 DB. Whenever I try to run a simple java code like:
List<User> users = service.findAllUsers();
I get the following error:
PSQLException: ERROR: relation "TABLE_NAME" does not exist
Since I have option hibernate.show_sql option set to true, I can see that hibernate is trying to run the following SQL command:
select this_.USERNAME as USERNAME0_0_, this_.PASSWORD as PASSWORD0_0_
from "TABLE_NAME" this_
When in reality, it should at least run something like:
select this_."USERNAME" as USERNAME0_0_, this_."PASSWORD" as PASSWORD0_0_
from "SCHEMA_NAME"."TABLE_NAME" as this_
Does anyone know what changes I need to make for Hibernate to produce the right SQL for PostgreSQL?
I have set up the necessary postgreSQL datasource in applicationContext.xml file:
<!-- Use Spring annotations -->
<context:annotation-config />
<!-- postgreSQL datasource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url"
value="jdbc:postgresql://localhost/DB_NAME:5432/SCHEMA_NAME" />
<property name="username" value="postgres" />
<property name="password" value="password" />
<property name="defaultAutoCommit" value="false" />
</bean>
On the same file I have set up the session factory with PostgreSQL dialect:
<!-- Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.myPackage.dbEntities.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- setup transaction manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
Finally, the way I am mapping the domain class to the table is:
@Entity
@Table(name = "`TABLE_NAME`")
public class User {
@Id
@Column(name = "USERNAME")
private String username;
Has anyone encountered a similar error?. Any help in solving this issue will be much appreciated.
Please note that question is different to post Cannot simply use PostgreSQL table name (”relation does not exist”)
Apologies for the lengthy post.