import sqlite3
class sqliteDb:
def __init__(self,dbName):
self.dbName=dbName
self.conn = sqlite3.connect(self.dbName)
#关闭sqlite只读模式
self.conn.execute("PRAGMA read_only = OFF")
self.cursor = self.conn.cursor()
def insert(self,tableName,data):
if not self.isTableExists(tableName):
# 创建表
self.cursor.execute(f"CREATE TABLE {tableName} (id INTEGER PRIMARY KEY AUTOINCREMENT,site_url varchar(50),site_title varchar(50));")
fieldList = []
valueList = []
for key in data:
fieldList.append(key)
valueList.append('"'+data[key]+'"')
fields = ','.join(fieldList)
values = ','.join(valueList)
insertSql = f"INSERT INTO {tableName} ({fields}) VALUES ({values})"
#print(insertSql)
return self.cursor.execute(insertSql)
def update(self,tableName,where,data):
setValueList = []
for key in data:
setValueList.append(key+'="'+data[key]+'"')
setValues = ','.join(setValueList)
return self.cursor.execute(f"UPDATE {tableName} set {setValues} WHERE {where}")
def select(self,tableName,field='*',where=''):
if not self.isTableExists(tableName):
return []
self.cursor.execute(f"SELECT {field} FROM {tableName}")
return self.cursor.fetchall()
def isTableExists(self,tableName):
self.cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name='{tableName}';")
result = self.cursor.fetchone()
return bool(result)
def __del__(self):
self.cursor.close()
self.conn.commit()
self.conn.close()
【python】sqlite操作类
于 2023-12-11 17:23:46 首次发布