#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sqlite3
class DBSqlite():
""" sqlite3数据库相关操作 """
def __init__(self):
pass
def createOperate(self,dbFile):
"""创建数据库操作"""
# 初始数据:
if os.path.isfile(dbFile,createSql):
print("-- remove s%--" %dbFile)
os.remove(dbFile)
conn = sqlite3.connect(dbFile)
try:
cursor = conn.cursor()
cursor.execute(createSql)
cursor.close()
conn.commit()
except:
pass
finally:
conn.close()
print("create dbs close")
def insertOperate(self,dbFile,insertSql):
"""插入操作"""
conn = sqlite3.connect(dbFile)
try:
cursor = conn.cursor()
cursor.execute(insertSql)
# cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")
# cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")
cursor.close()
conn.commit()
except:
pass
finally:
conn.close()
print("insert dbs close")
def queryOperate(self,dbFile,querySql):
"""查询操作"""
conn = sqlite3.connect(dbFile)
try:
cursor = conn.cursor()
cursor.execute(r"SELECT * FROM user ;")
values = cursor.fetchall()
cursor.close()
conn.commit()
except:
pass
finally:
conn.close()
# print(values)
print("query dbs close")
return values
def deleteOperate(self):
"""删除操作"""
if __name__ == '__main__':
print("--main--")
dbFile = os.path.join(os.path.dirname(__file__), 'test.db')
createSql = 'create table user(id varchar(20) primary key, name varchar(20), score int)'
insertSql = r"insert into user values ('A-005', 'Ddam', 97)"
querySql = r"SELECT * FROM user;"
# print(dbFile)
dbs = DBSqlite()
# dbs.createOperate(dbFile,createSql)
dbs.insertOperate(dbFile,insertSql)
result = dbs.queryOperate(dbFile,querySql)
print(result)
print("--end--")