我是Python的新手。我刚刚创建了一个sqlite3 db包装类来处理我的应用程序中的数据库交互。我的问题是如何从我的db包装器类方法,addRow,updRow(添加和更新行)返回成功/失败消息到调用程序?
这是我到目前为止拼凑的课程代码: -
class dbManager(object):
def __init__(self, db):
self.conn = lite.connect(db)
self.conn.execute('pragma foreign_keys = on')
self.conn.execute('pragma synchronous=off')
self.conn.commit()
self.cur = self.conn.cursor()
def query(self, arg):
self.cur.execute(arg)
self.conn.commit()
return self.cur
def addRow(self, tablename, data):
"""
Insert data into a table. The data does not have to be escaped.
"""
global actInserts
# Create a new cursor
# tc = self.conn.cursor() # opened at init
tablelist = ""
valueholder = ""
valuelist = []
for key, value in data.items():
if len(tablelist) > 0:
tablelist += ', '
valueholder += ', '
# Add to table column list
tablelist += key
# Add a holder
valueholder += '?'
# build the insert values
valuelist.append(value)
# Perform and commit the insert
try:
dbResponse = self.cur.execute("INSERT INTO " + tablename + " (" + tablelist + ") VALUES (" + valueholder + ");", valuelist)
actInserts += 1
except lite.Error, e:
dbResponse = 'Sqlite Error NP: ' + e.args[0]
print 'Sqlite Error NP: ' + e.args[0]
return dbResponse
def closeConnection (self):
self.conn.commit()
self.conn.close()
def __del__(self):
self.conn.close()
答案 0 :(得分:0)
我认为有两种方法可以做到这一点。你可以:
我认为选项2是更好的方法。
此外,我认为您的查询构建将更清晰(或至少更简洁)使用类似以下内容(假设数据是字典)
tablelist = ','.join(list(data.viewkeys()))
valueholder = ','.join(['?' for i in data.viewkeys()])
valuelist = list(data.viewvalues())