class部分:
class Database(object):
filepath = 'db路径'
def __init__(self, database=None):
self.database = self.filepath if database is None else database
self.connection = None
self.cursor = None
def __del__(self):
self.disconnect()
def connect(self, who="server"):
self.connection = sqlite3.connect(self.database, timeout=3, isolation_level=None, check_same_thread=False)
self.cursor = self.connection.cursor()
def disconnect(self):
if self.cursor:
self.cursor.close()
if self.connection:
self.connection.close()
def commit(self):
self.connection.commit()
def execute(self, statement, arguments=None):
while True:
try:
if arguments:
self.cursor.execute(statement, arguments)
else:
self.cursor.execute(statement)
self.commit()
except sqlite3.OperationalError, ex:
raise
else:
break
if statement.lstrip().upper().startswith("SELECT"):
return self.cursor.fetchall()
def init(self):
self.execute("CREATE TABLE data("
"id integer primary key autoincrement, "
"status CHAR(16), "
"result CHAR(8192), "
"object CHAR(1024)"
")")
实例化使用:
db = Database()
db.connect()
db.execute("update data set result=? where id=?",(result, id))
db.execute("update data set status='done' where id='{}'".format(id))
select_result = db.execute("select status from data where id='{}'".format(id))