Python3操作 SQLite
import os
import sqlite3
class SQLiteTools():
def __init__(self):
pass
def createConnection(self, DB_name):
''' 创建数据库连接 '''
self.con = sqlite3.connect(DB_name)
self.cur = self.con.cursor()
def selectTableExist(self, tbname):
'''
判断指定数据表是否存在
:param tbname: 数据表名称
:return: 存在范围True,否则返回False
'''
sql = "select * from sqlite_master where type='table' and name = '" + tbname + "';"
self.cur.execute(sql)
cursor = self.cur.fetchall()
if cursor:
return True
else:
return False
def createSQLtable(self, tbname):
'''
创建通用数据表,默认第一列为主键,名称:ID,类型:INTEGER, 自增
:param tbname: 数据表名称
'''
sql = u"CREATE TABLE if not exists " + tbname + u" (ID INTEGER PRIMARY KEY AUTOINCREMENT);"
self.cur.execute(sql)
self.con.commit()
def addSQLtableColumn(self, tbname, columnName, genre):
'''
指定数据表添加列
:param tbname: 表名
:param columnName: 列名
:param genre: 添加列类型
'''
sql = u"ALTER TABLE " + tbname + u" ADD " + columnName + " " + genre +";"
self.cur.execute(sql)
self.con.commit()
def addSQLtableRow(self, tbname, rowNum):
'''
指定数据表添加指定行
:param tbname: 表格名称
:param rowNum: 行数
:return: None
'''
rownum = [(i,) for i in range(rowNum)]
sql = "INSERT INTO " + tbname + " (ID) VALUES (?);"
self.cur.executemany(sql, rownum)
self.con.commit()
def setSQLtableValue(self, tbname, column, row, value):
'''
更新数据表指定位置的值
:param tbname: 数据表名称
:param row: 行数
:param column: 列数
:param value: 值
'''
sql = u"UPDATE " + tbname + u" SET " +column+ "='" +value+ "' WHERE ID=" +str(row)+ ";"
self.cur.execute(sql)
self.con.commit()
def getSQLtableRowNum(self, tbname):
'''
获取指定表格总行数
:param tbname: 表格名称
:return: 行数
'''
result = 0
sql = "SELECT COUNT(*) FROM " + tbname + ";"
self.cur.execute(sql)
for value in self.cur:
return value[0]
return result
def getSQLtableColumnName(self, tbname):
'''
获取指定表所有字段名称
:param taname: 表格名称
:return: 返回列名称列表
'''
sql = "PRAGMA table_info([" +tbname+ "])"
self.cur.execute(sql)
NameList = []
for value in self.cur:
result = value[1]
if result and result != "ID":
NameList.append(result)
return NameList
def getSQLtableValue(self, tbname, column, row):
'''
读取指定数据表的指定数据
:param tbname: 数据表名称
:param row: 数据表行
:param column: 数据表列
:return 返回查询到的值
'''
sql = "SELECT " +column+ " FROM " +tbname+ " WHERE ID=" +str(row)+ ";"
self.cur.execute(sql)
for value in self.cur:
return value[0]
def getSQLtableColumn(self, tbname, column):
'''
读取数据表指定列的所有数据
:param tbname: 数据表名称
:param column: 列名称
:return 返回查询到的值列表
'''
sql = "SELECT " +column+ " FROM " +tbname+ ";"
valueList = []
self.cur.execute(sql)
for value in self.cur:
valueList.append(value[0])
return valueList
def getSQLtableRow(self, tbname, row):
'''
获取指定表格指定行数据
:param tbname: 表格名称
:param row: 行数
:return: 值列表
'''
sql = "SELECT * FROM " + tbname + " WHERE ID="+ str(row) +";"
self.cur.execute(sql)
for value in self.cur:
valueList = list(value)
valueList.pop(0)
return valueList
def delSQLtableRow(self, tbname, startRow, rowNum=1):
'''
指定数据表删除指定行数
:param tbname: 表格名称
:param rowNum: 开始行数
:param rowNum: 行数
'''
rowList = [(i,) for i in range(startRow, startRow+rowNum)]
sql = "DELETE FROM " + tbname + " WHERE ID = ?;"
self.cur.executemany(sql, rowList)
self.con.commit()
def delSQLtableColumn(self, tbname, columnName):
'''
指定数据表删除指定列
SQLite不支持删除列操作,采用复制新表的方式。
:param tbname: 表名
:param columnName: 列名
:param genre: 添加列类型
'''
tbName = "tbName0"
CloumnNameList = self.getSQLtableColumnName(tbname)
if columnName in CloumnNameList:
CloumnNameList.remove(columnName)
CloumnNameList.insert(0, "ID")
strName = ','.join(CloumnNameList)
sql = u"create table "+tbName+" as select "+strName+" from "+tbname+" where 1 = 1"
self.cur.execute(sql)
self.con.commit()
self.delSQLtable(tbname)
self.removeSQLtableName(tbName, tbname)
def removeSQLtableName(self, tbname, newTbname):
'''
重命名表格
:param oldTbName: 旧表格名称
:param newTbName: 新表格名称
:return: None
'''
sql = u"alter table "+tbname+" rename to "+newTbname+";"
self.cur.execute(sql)
self.con.commit()
def ClearSQLtable(self, tbname):
'''
清空指定数据表
:param tbname: 表名
'''
sql = "DELETE FROM " +tbname+ ";"
self.cur.execute(sql)
self.con.commit()
def delSQLtable(self, tbname):
'''
删除指定表
:param tbname:
:return: None
'''
sql = u"drop table "+tbname+";"
self.cur.execute(sql)
self.con.commit()
if __name__ == '__main__':
print("Python SQLite实例")
class sqliteTest():
def __init__(self):
self.DB_File = "./sqlite.db"
self.tableName = "sqlite"
if os.path.exists(self.DB_File):
os.remove(self.DB_File)
self.sqlite = SQLiteTools()
self.sqlite.createConnection(self.DB_File)
def createTable(self):
if not self.sqlite.selectTableExist(self.tableName):
self.sqlite.createSQLtable(self.tableName)
def addData(self):
self.sqlite.addSQLtableColumn(self.tableName, "month1", "text")
self.sqlite.addSQLtableColumn(self.tableName, "month2", "text")
self.sqlite.addSQLtableColumn(self.tableName, "month3", "text")
self.sqlite.addSQLtableColumn(self.tableName, "month4", "text")
self.sqlite.addSQLtableRow(self.tableName, 30)
self.sqlite.setSQLtableValue(self.tableName, "month1", 0, "1-0")
self.sqlite.setSQLtableValue(self.tableName, "month1", 1, "1-1")
self.sqlite.setSQLtableValue(self.tableName, "month2", 2, "2-2")
self.sqlite.setSQLtableValue(self.tableName, "month2", 3, "2-3")
def getData(self):
value = self.sqlite.getSQLtableRowNum(self.tableName)
print("数据表总行数:", value)
value = self.sqlite.getSQLtableColumnName(self.tableName)
print("所有列的名称(不包括ID):", value)
value = self.sqlite.getSQLtableValue(self.tableName, "month1", 0)
print("month1列,第一行的值: ", value)
value = self.sqlite.getSQLtableColumn(self.tableName, "month2")
print("month2列的所有值: ", value)
value = self.sqlite.getSQLtableRow(self.tableName, 1)
print("第二行的所有值(不包括ID): ", value)
def delData(self):
value = self.sqlite.getSQLtableRowNum(self.tableName)
print("删除前数据表总行数:", value)
self.sqlite.delSQLtableRow(self.tableName, 10, 5)
value = self.sqlite.getSQLtableRowNum(self.tableName)
print("删除后数据表总行数:", value)
value = self.sqlite.getSQLtableColumnName(self.tableName)
print("删除前所有列名(不包括ID)", value)
self.sqlite.delSQLtableColumn(self.tableName, "month3")
value = self.sqlite.getSQLtableColumnName(self.tableName)
print("删除后所有列名(不包括ID)", value)
self.sqlite.ClearSQLtable(self.tableName)
self.sqlite.delSQLtable(self.tableName)
win = sqliteTest()
win.createTable()
win.addData()
win.getData()
win.delData()
PyQt5 操作 SQLite
import os
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
class SQLiteTools():
def __init__(self):
pass
def createConnection(self, DB_name):
'''
创建数据库连接
:param DB_name: 数据库名称
:return: null
'''
db=QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(DB_name)
db.open()
self.que = QSqlQuery()
def selectTableExist(self, tbname):
'''
判断指定数据表是否存在
:param tbname: 表格名称
:return: 在返回True,否则返回False
'''
sql = u"select * from sqlite_master where type='table' and name = '" + tbname + u"';"
self.que.exec_(sql)
return self.que.next()
def createSQLtable(self, tbname):
'''
创建通用数据表,默认第一列为主键,名称:ID,类型:INTEGER, 自增
:param tbname: 数据表名称
:return: null
'''
sql = u"CREATE TABLE if not exists " + tbname + u" (ID INTEGER PRIMARY KEY AUTOINCREMENT);"
self.que.exec_(sql)
def addSQLtableColumn(self, tbname, columnName, genre):
'''
指定数据表添加列
:param tbname: 表名
:param columnName: 列名
:param genre: 添加列类型
:return: null
'''
sql = u"ALTER TABLE " + tbname + u" ADD " + columnName + " " + genre +";"
self.que.exec_(sql)
def addSQLtableRow(self, tbname, rowNum):
'''
指定数据表添加指定行
:param tbname: 表格名称
:param rowNum: 行数
:return: null
'''
for row in range(rowNum):
sql = "INSERT INTO " + tbname + " (ID) VALUES (" + str(row) + ");"
self.que.exec_(sql)
def setSQLtableValue(self, tbname, column, row, value):
'''
更新数据表指定位置的值
:param tbname: 数据表名称
:param column: 行数
:param row: 列数
:param value: 值
:return: null
'''
sql = u"UPDATE " + tbname + u" SET " +column+ "='" +value+ "' WHERE ID=" +str(row)+ ";"
self.que.exec_(sql)
def getSQLtableRowNum(self, tbname):
'''
获取指定表格总行数
:param tbname: 表格名称
:return: 行数
'''
result = 0
sql = "SELECT COUNT(*) FROM " + tbname + ";"
self.que.exec_(sql)
if self.que.next():
result = self.que.value(0)
return result
def getSQLtableColumnName(self, tbname):
'''
获取指定表所有字段名称
:param taname: 表格名称
:return: 列名称列表
'''
sql = "PRAGMA table_info([" +tbname+ "])"
self.que.exec_(sql)
NameList = []
while self.que.next():
result = self.que.value(1)
if result and result != "ID":
NameList.append(result)
return NameList
def getSQLtableValue(self, tbname, column, row):
'''
读取指定数据表的指定数据
:param tbname: 数据表名称
:param row: 数据表行
:param column: 数据表列
:return: 值
'''
value = 0
sql = "SELECT " +column+ " FROM " +tbname+ " WHERE ID=" +str(row)+ ";"
self.que.exec_(sql)
if self.que.next():
value = self.que.value(0)
return value
def getSQLtableColumn(self, tbname, column):
'''
读取数据表指定列的所有数据
:param tbname: 数据表名称
:param column: 列名称
:return: 值列表
'''
sql = "SELECT " +column+ " FROM " +tbname+ ";"
value_list = []
if self.que.exec_(sql):
column_index = self.que.record().indexOf(column)
while self.que.next():
value = self.que.value(column_index)
value_list.append(value)
return value_list
def getSQLtableRow(self, tbname, row):
'''
获取指定表格指定行数据
:param tbname: 表格名称
:param row: 行数
:return: 值列表
'''
columnNum = len(self.getSQLtableColumnName(tbname))
sql = "SELECT * FROM " + tbname + " WHERE ID="+ str(row) +";"
self.que.exec_(sql)
valueList = []
while self.que.next():
for i in range(1, columnNum+1):
result = self.que.value(i)
valueList.append(result)
return valueList
def delSQLtableColumn(self, tbname, columnName):
'''
指定数据表删除指定列
SQLite不支持删除列操作,采用复制新表的方式。
:param tbname: 表名
:param columnName: 列名
:return: null
'''
tbName = "tbName0"
CloumnNameList = self.getSQLtableColumnName(tbname)
if columnName in CloumnNameList:
CloumnNameList.remove(columnName)
CloumnNameList.insert(0, "ID")
strName = ','.join(CloumnNameList)
sql = u"create table "+tbName+" as select "+strName+" from "+tbname+" where 1 = 1"
self.que.exec_(sql)
self.delSQLtable(tbname)
self.removeSQLtableName(tbName, tbname)
def delSQLtableRow(self, tbname, startRow, rowNum=1):
'''
指定数据表删除指定行数
:param tbname: 表格名称
:param startRow: 开始行数
:param rowNum: 要删除总行数
:return: null
'''
for row in range(startRow, startRow + rowNum):
sql = "DELETE FROM " + tbname + " WHERE ID = " + str(row) + ";"
self.que.exec_(sql)
def removeSQLtableName(self, tbname, newTbname):
'''
重命名表格
:param tbname: 旧表格名称
:param newTbname: 新表格名称
:return: null
'''
sql = u"alter table "+tbname+" rename to "+newTbname+";"
self.que.exec_(sql)
def ClearSQLtableRowValue(self, tbname):
'''
清空指定数据表
:param tbname: 表名
:return: null
'''
sql = "DELETE FROM " +tbname+ ";"
self.que.exec_(sql)
def delSQLtable(self, tbname):
'''
删除指定表
:param tbname:
:return: null
'''
sql = u"drop table "+tbname+";"
self.que.exec_(sql)
if __name__ == '__main__':
print("PyQt5 SQLite实例")
class sqliteTest():
def __init__(self):
self.PathFile = "./sqlite.db"
self.tableName = "sqlite"
if os.path.exists(self.PathFile):
os.remove(self.PathFile)
self.sqlite = SQLiteTools()
self.sqlite.createConnection(self.PathFile)
def createTable(self):
if not self.sqlite.selectTableExist(self.tableName):
self.sqlite.createSQLtable(self.tableName)
def addData(self):
self.sqlite.addSQLtableColumn(self.tableName, "month1", "text")
self.sqlite.addSQLtableColumn(self.tableName, "month2", "text")
self.sqlite.addSQLtableColumn(self.tableName, "month3", "text")
self.sqlite.addSQLtableColumn(self.tableName, "month4", "text")
self.sqlite.addSQLtableRow(self.tableName, 30)
self.sqlite.setSQLtableValue(self.tableName, "month1", 0, "1-0")
self.sqlite.setSQLtableValue(self.tableName, "month1", 1, "1-1")
self.sqlite.setSQLtableValue(self.tableName, "month2", 2, "2-2")
self.sqlite.setSQLtableValue(self.tableName, "month2", 3, "2-3")
def getData(self):
value = self.sqlite.getSQLtableRowNum(self.tableName)
print("数据表总行数:", value)
value = self.sqlite.getSQLtableColumnName(self.tableName)
print("所有列的名称(不包括ID列):", value)
value = self.sqlite.getSQLtableValue(self.tableName, "month1", 0)
print("month1列,第一行的值:", value)
value = self.sqlite.getSQLtableColumn(self.tableName, "month2")
print("month2列的所有值:", value)
value = self.sqlite.getSQLtableRow(self.tableName, 2)
print("第三行的所有值(不包括ID): ", value)
def delData(self):
value = self.sqlite.getSQLtableRowNum(self.tableName)
print("删除前数据表总行数:", value)
self.sqlite.delSQLtableRow(self.tableName, 10, 5)
value = self.sqlite.getSQLtableRowNum(self.tableName)
print("删除后数据表总行数:", value)
value = self.sqlite.getSQLtableColumnName(self.tableName)
print("删除前所有列名(不包括ID):", value)
self.sqlite.delSQLtableColumn(self.tableName, "month3")
value = self.sqlite.getSQLtableColumnName(self.tableName)
print("删除后所有列名(不包括ID)", value)
self.sqlite.ClearSQLtableRowValue(self.tableName)
self.sqlite.delSQLtable(self.tableName)
win = sqliteTest()
win.createTable()
win.addData()
win.getData()
win.delData()