[英]psycopg2 connecting to postgresql database - error
I have problem to connect to my postgreSQL database.我无法连接到我的 postgreSQL 数据库。 I have databasename
, password
, hostname
, port
and I use this:我有databasename
, password
, hostname
, port
,我使用这个:
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"
But I got error like this:但我得到了这样的错误:
Is the server running on host "...." and accepting TCP/IP connections on port 5432服务器是否在主机“....”上运行并接受端口 5432 上的 TCP/IP 连接
I don't know if I used correctly host, I insert the value of hostname.我不知道我是否正确使用了主机,我插入了主机名的值。
What is the difference between hostname and host?主机名和主机有什么区别? Anyone could help me?任何人都可以帮助我吗?
psycopg2.connect(dbname=dbname, user=user, password=password, host=postgres_address, port=postgres_port)
This is working example to connect, you must define early dbname, user, password, postgres_address.这是连接的工作示例,您必须定义早期的 dbname、用户、密码、postgres_address。 If you have connection error, you can use ping for testing connection and telnet for testing openning port.如果出现连接错误,可以使用 ping 测试连接和 telnet 测试开放端口。 Or you can use Beaver for test connection to postgres server.或者您可以使用 Beaver 测试与 postgres 服务器的连接。
很可能您的数据库有防火墙,请务必将您尝试连接的 IP 列入白名单。
host
and hostname
host
hostname
和hostname
区别The difference of host
and hostname
really depends on the context. host
和hostname
的区别实际上取决于上下文。 In your context of psycopg2
and PostgreSQL
connection, the host
normally means the IP address of the PostgreSQL server or the resolvable name of the PostgreSQL server such as DNS name if it has.在psycopg2
和PostgreSQL
连接的上下文中, host
通常表示 PostgreSQL 服务器的 IP 地址或 PostgreSQL 服务器的可解析名称,例如 DNS 名称(如果有)。 If you are running linux server, the output of command hostname
is unlikely to work in your case.如果您正在运行 linux 服务器,则命令hostname
的输出不太可能适用于您的情况。
psycopg2
connection psycopg2
连接Your connection string looks OK.您的连接字符串看起来不错。 But I will suggest you to use below connection format:但我建议您使用以下连接格式:
import psycopg2
try:
connection = psycopg2.connect(user = "sysadmin",
password = "pynative@#29",
host = "127.0.0.1",
port = "5432",
database = "postgres_db")
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL", error)
You should use the IP address as the host
value.您应该使用 IP 地址作为host
值。
In the case of connection error, you should use other tools to test the connection of PostgreSQL server such as psql
, pgAdmin4
or DBeaver
.在连接错误的情况下,您应该使用其他工具来测试 PostgreSQL 服务器的连接,例如psql
、 pgAdmin4
或DBeaver
。
You can also use telnet
or netcat
tools to test the network connection of PostgreSQL server, such as也可以使用telnet
或netcat
工具测试PostgreSQL服务器的网络连接情况,如
telnet PostgreSQL_ip_address 5432
nc -v PostgreSQL_ip_address 5432
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.