Python:无法连接数据库

时间:2014-08-04 11:14:39

标签: python database postgresql psycopg2

Python 3.4 with psycopg2

我使用this guide设置基本psycopg2连接,如下所示:

#!/usr/bin/python
import psycopg2
import sys
import pprint

def main():
    conn_string = "dbname='CIBTST' host='XX.XX.XXX.XX' port='XXXX' user='XXXXX' password='XXXX'"
    conn = psycopg2.connect(conn_string)
    cursor = conn.cursor()
    cursor.execute("My_select")
    records = cursor.fetchall()
    pprint.pprint(records)
if __name__ == "__main__":
    main()

我得到了这个追溯:

Traceback (most recent call last):
File "C:\Users\pi24926\Desktop\Python\doSMS.py", line 14, in <module>
main()
File "C:\Users\pi24926\Desktop\Python\doSMS.py", line 8, in main
conn = psycopg2.connect(conn_string)
File "C:\Python34\lib\site-packages\psycopg2\__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError

当我在另一个客户端(Toad)中尝试相同的select语句时,它似乎正常运行。任何建议都会很棒。谢谢!

编辑:问题的根源是:PORT。如果我跑:

#!/usr/bin/python
import psycopg2
import sys
import pprint

def main():
    conn_string = "dbname='CIBTST' host='XX.XX.XXX.XX' user='XXXXX' password='XXXX'"
    conn = psycopg2.connect(conn_string)
    cursor = conn.cursor()
    cursor.execute("My_select")
    records = cursor.fetchall()
    pprint.pprint(records)
if __name__ == "__main__":
    main()

然后我得到:

Traceback (most recent call last):
File "C:\Users\pi24926\Desktop\Python\doSMS.py", line 14, in <module>
main()
File "C:\Users\pi24926\Desktop\Python\doSMS.py", line 8, in main
conn = psycopg2.connect(conn_string)
File "C:\Python34\lib\site-packages\psycopg2\__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: Connection timed out  (0x0000274C/10060)
Is the server running on host "XXXXXXX" and accepting
TCP/IP connections on port 5432?

由于某种原因,我只能在端口1522下连接。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

问题出在数据库......

这是一个Oracle,所以我应该使用cx_Oracle而不是psycopg2。