dms-client/util/simple_sqlite3_tool.py

96 lines
2.2 KiB
Python
Raw Normal View History

2022-02-15 15:41:45 +08:00
# coding: utf-8
2022-02-28 13:51:30 +08:00
# Authortajochen
2022-02-15 15:41:45 +08:00
import sqlite3
import os
class SimpleSQLite3Tool:
"""
simpleToolSql for sqlite3
简单数据库工具类
编写这个类主要是为了封装sqlite继承此类复用方法
"""
2022-02-28 13:51:30 +08:00
def __init__(self, filename="stsql"):
"""
初始化数据库默认文件名 stsql.db
filename文件名
"""
self.filename = filename
self.db = sqlite3.connect(self.filename)
self.c = self.db.cursor()
2022-02-15 15:41:45 +08:00
2022-02-28 13:51:30 +08:00
def close(self):
"""
关闭数据库
"""
self.c.close()
self.db.close()
def execute(self, sql, param=None):
"""
执行数据库的增
sqlsql语句
param数据可以是list或tuple亦可是None
return成功返回True
"""
try:
2022-02-15 15:41:45 +08:00
if param is None:
self.c.execute(sql)
else:
2022-02-28 13:51:30 +08:00
if type(param) is list:
self.c.executemany(sql, param)
else:
self.c.execute(sql, param)
count = self.db.total_changes
self.db.commit()
except Exception as e:
print(e)
return False, e
if count > 0:
return True
else:
return False
def query(self, sql, param=None):
"""
查询语句
sqlsql语句
param参数,可为None
return成功返回True
"""
if param is None:
self.c.execute(sql)
else:
self.c.execute(sql, param)
return self.c.fetchall()
2022-02-15 15:41:45 +08:00
2022-02-28 13:51:30 +08:00
# def set(self,table,field=" * ",where="",isWhere=False):
# self.table = table
# self.filed = field
# if where != "" :
# self.where = where
# self.isWhere = True
# return True
2022-02-15 15:41:45 +08:00
if __name__ == "__main__":
# 数据库文件位置
2022-02-28 13:51:30 +08:00
sql = SimpleSQLite3Tool("../test.db")
f = sql.execute("create table test (id int not null,name text not null,age int);")
print("ok")
sql.execute("insert into test (id,name,age) values (?,?,?);", [(1, 'abc', 15), (2, 'bca', 16)])
res = sql.query("select * from test;")
print(res)
sql.execute("insert into test (id,name) values (?,?);", (3, 'bac'))
res = sql.query("select * from test where id=?;", (3,))
2022-02-15 15:41:45 +08:00
res = sql.query("select * from data_collection_info;")
print(res)
sql.close()