2017-06-06 49 views
0

我試圖通過Python 2.7,此代碼連接到我的數據庫連接到Postgres數據庫:通過Python

import csv 
import psycopg2 

try: 
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'") 
    cursor = conn_cursor() 
    reader = csv.reader(open('last_file.csv', 'rb')) 
    print "connected" 
except: 
    print "not Connected" 

上週所做的工作,我們不認爲我們已經改變了什麼,但現在它不會連接。 我們已經嘗試在數據庫打開和關閉時使用它,沒有任何工作。 該數據庫確實存在於Postgres中。

+2

而不是捕捉異常並隱藏有關它的所有信息,爲什麼不讓異常拋出,以便您可以看到堆棧跟蹤? – khelwood

回答

0

例外部分添加這樣的,看看有什麼錯誤

except Exception as ex: 

    print "not Connected" 

    print "Error: "+ str(ex) 
0

試試這個:

import csv 
import psycopg2 

try: 
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'") 
except: 
    print "I am unable to connect to the database." 
    cursor = conn.cursor() 
try: 
    reader = csv.reader(open('last_file.csv', 'rb')) 
    print "connected" 
except: 
    print "not Connected" 
0
import psycopg2 

try: 
    conn = psycopg2.connect("dbname='database_name' user='postgres_user_name' host='localhost' password='user_passwd'") 
except: 
    print "I am unable to connect to the database" 



cur = conn.cursor() 
cur.execute("""SELECT * from table_name""") 
rows = cur.fetchall() 
print "\nShow me the data:\n" 
for row in rows: 
    print " ", row[0] 
    print " ", row[1] 
0

好像有什麼問題你的Postgres。

試試看看postgres日誌。 默認情況下postgres日誌的位置: tail -f/var/log/postgresql/<> /main/postgresql.log 這樣的事情。

另外不要忘記檢查防火牆。也許有人不小心禁用它。