2013-06-26 24 views
0

嘗試設置一個類,該類將數據庫光標傳遞回來,以便在各種函數中使用。下面的代碼不起作用Python:將一個光標從一個類傳回給一個dbi實例

class create_db(object): 
    def __init__(self): 
     import psycopg2 as pq 
     self.cn = pq.connect('dbname=mydb user=me') 
     self.cr = self.cn.cursor() 

我想什麼,能夠做的就是

cur = create_db() 
cur.execute('SELECT * FROM table1;') 

我怎樣才能改變我的代碼來解決這個問題。

回答

1

根據您想要做

class create_db(object): 

    def __init__(self): 
     import psycopg2 as pq 
     self.cn = pq.connect('dbname=mydb user=me') 
     self.cr = self.cn.cursor() 

    def execute(self, query, *args): 

     results = self.cr.execute(query, args) 

     return results 

現在你可以運行類似

cur.execute('SELECT * FROM table1 WHERE column = ?;', (42,)) 

我不記得了我的頭頂部,但我想你會什麼想在您的SQL語句結尾處省略;

相關問題