Перейти к содержимому

Как узнать адрес базы данных postgresql

  • автор:

Как мне найти URL-адрес моей базы данных для подключения к postgres? [Дубликат]

Если вы сохраняете с помощью XmlWriter, то по умолчанию параметры имеют отступ с двумя пробелами и заменяют окончания строки CR / LF. Вы можете настроить эти параметры после создания записи или создать запись с объектом XmlSettings, настроенным с учетом ваших потребностей.

9 ответов

Я нашел отзыв о подсказке полезным, чтобы устранить эту проблему в Tomcat —

, обязательно загрузите драйвер, сначала выполнив Class.forName («org.postgresql.Driver»); в вашем коде.

Код jdbc работал нормально как автономная программа, но в TOMCAT он дал ошибку «Не найден подходящий драйвер»

Этот URL-адрес выглядит неправильно, вам нужно следующее:

Возможно, стоит отметить, что это также может произойти, когда Windows блокирует загрузки, которые он считает небезопасными. Это можно устранить, щелкнув правой кнопкой мыши файл jar (например, ojdbc7.jar) и проверив поле «Unblock» внизу.

Диалоговое окно свойств файла JAR для Windows: Windows JAR File Properties Dialog[/g0]

Позорное java.sql.SQLException: не найдено подходящего драйвера

Это исключение может иметь в основном две причины:

1. Драйвер JDBC не загружен

Вам необходимо убедиться, что драйвер JDBC помещен в собственную папку /lib сервера.

[/g15]

Или, если на самом деле вы не используете источник данных пула соединений, управляемый сервером, а вручную запускаете DriverManager#getConnection() в WAR , тогда вам нужно поместить драйвер JDBC в WAR /WEB-INF/lib и выполнить ..

.. в вашем коде перед первый DriverManager#getConnection() вызов, посредством которого вы делаете убедитесь, что вы не проглатываете / игнорируете любые ClassNotFoundException , которые могут быть выброшены им, и продолжайте поток кода, как будто ничего исключительного не произошло. См. Также Где я должен разместить драйвер JDBC для пула соединений Tomcat?

2. Или URL-адрес JDBC находится в неправильном синтаксисе

Вам нужно убедиться, что URL JDBC соответствует документации драйвера JDBC и помните, что он обычно чувствителен к регистру. Когда URL-адрес JDBC не возвращает true для Driver#acceptsURL() для любого из загруженных драйверов, тогда вы также получите именно это исключение.

В случае PostgreSQL это документально здесь .

С JDBC база данных представлена ​​URL-адресом (Uniform Resource Locator). С PostgreSQL ™ это принимает одну из следующих форм:

  • jdbc:postgresql:database
  • jdbc:postgresql://host/database
  • jdbc:postgresql://host:port/database

В случае с MySQL это здесь .

Общий формат URL-адреса JDBC для подключения к серверу MySQL следующим образом: элементы в квадратных скобках ( [ ] ) являются необязательными:

jdbc:mysql://[host1][:port1][,[host2][:port2]]. [/[database]] » [?propertyName1=propertyValue1[&propertyName2=propertyValue2]. ]

В случае Oracle это документировано здесь .

Существует 2 синтаксиса URL, старый синтаксис, который будет работать только с SID и новый с именем службы Oracle.

PostgreSQL, what is the hostname address of my default database?

I just created a PostgreSQL database on my laptop (following these instructions), which is running Linux CentOS 7.

Now I would like to understand what is the hostname address of my default database. I thought it was localhost but it’s not.

I want to get to know the name or the IP address to use with the psql -h command. Basically, running this psql -h HOSTNAME command should let me have the same result of the psql command alone, that is letting me connect to my database.

What is the hostname address of my default database?

● postgresql.service — PostgreSQL database server Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled) Active: active (running) since Thu 2017-03-30 14:40:30 EDT; 1 day 1h ago Main PID: 2256 (postgres

while both psql -h 127.0.0.1 and psql -h 127.0.0.1 -U davide produce this message:

psql: FATAL: Ident authentication failed for user «davide»`

finding local postgresql “database_url”

I’m following these instructions (https://github.com/assemblymade/assemblycoins) to get a postgresql server connected.

I am told to: «set DATABASE_URL local variable to postgres database url»

I’m not too sure where to find this, it doesn’t seem like an easy thing to find. (Sorry, i’m pretty new to Postgresql if this is a real amateur question)

For a bit more context, I installed postgresql from Enterprise DB and can successfully run a postgresql database on PGAdmin.

5 Answers 5

You can display your connection info if logged into postgres shell with command:

this will display the database you are connected to as well as the user logged on

See The docs The general form for a connection URI is:

You probably need to set you environment variable DATABASE_URL to something like

How to find the URL path to a local postgres database?-postgresql

Feel free to take out the db/ part of your database name — it's only warranted for databases like SQLite that store the db in a local file and need a filename.

Not sure how you're attempting to access the database, but if you are attempting to create a script that uses the same database as rails but is run separately, consider using a script that runs in rails. In unix/linux, if you add this line:

to the first line of your script and then make it executable with:

then you can simply run it with

and it can use your model classes just like your controller and view code in rails. Then there is no need to access the database manually.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *