Trying to set up a class that will pass a database cursor back that I can use in various functions. The code below doesn't work
class create_db(object):
def __init__(self):
import psycopg2 as pq
self.cn = pq.connect('dbname=mydb user=me')
self.cr = self.cn.cursor()
What I'd like to be able to do is
cur = create_db()
cur.execute('SELECT * FROM table1;')
How can I change my code to address that.
Based on what you'd like to do
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
now you can run something like
cur.execute('SELECT * FROM table1 WHERE column = ?;', (42,))
I can't remember off the top of my head but I think you'll want to omit the ;
at the end of your SQL statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.