python中sqlite的基本调用和数据库类的封装案例

python中sqlite的基本调用和数据库类的封装案例,第1张

前面的博文我们介绍了python中sqlite封装的基本 *** 作,完成了类的数据库名参数化封装,这篇博文将继续对数据库典型方法增删改查的具体封装逐一介绍。



一、数据表名的参数化
这里,我们还是通过类变量以及构造函数来传参

def __init__(self,dbName,tabName=''):
		self.conn=sqlite3.connect(dbName)
		self.csr=self.conn.cursor()
		print("Database", dbName, " created successfully!")
		if tabName=='':
			self.tabName='customer'

这里通过条件判断给了一个默认参数,我们也可以直接通过构造函数的参数列表给出默认值,但使用条件判断的方法我们会有更灵活的用法。


	def __init__(self,dbName,tabName='customer'):
		self.conn=sqlite3.connect(dbName)
		self.csr=self.conn.cursor()
		print("Database", dbName, " created successfully!")
		if tabName=='':
			self.tabName='customer'
		else:
			self.tabName=tabName

最后,执行创建表的sql语句即可

self.csr.execute('''create table if not exists '''+self.tabName+''' (ide int,name text,age int)''')


二、插入记录的参数化
1、单条记录插入参数化

def addRecord(self,ids,name,age):
		self.csr.execute("insert into customer (ide,name,age) values (?,?,?) ",(ids,name,age))
		print("one record inserted successfully")

我们可以采用最原始的方法调用

dh = DBHhelper("mydb1.db")
dh.addRecord(13,'Doson',33)

也可以采用元组作为参数一次性传递三个参数

dh = DBHhelper("mydb1.db")
info=(13,'Doson',33)
dh.addRecord(*info)

单条记录的插入,我们还可以直接使用元组来作为参数,那么参数表达式列表就更干净了

def addRecord(self,infos):
	self.csr.execute("insert into customer  values (?,?,?) ",(infos))

调用的时候也会方便一些,调用方法如下:

dh = DBHhelper("mydb1.db")
info=(13,'Doson',33)
dh.addRecord(info)

或者直接写

dh = DBHhelper("mydb1.db")
dh.addRecord((13,'Doson',33))

2、批量插入记录参数化
批量插入的应用场景是比较多的,尤其将其他数据库的数据如Excel中的数据导入我们的应用程序就可以用批量插入,我们可以如下封装

def addRecords(self,infos):
		self.csr.executemany("insert into "+self.tabName+" (ide, name, age) values (?,?,?)",infos)
		print("record inserted successfully!")

或者可以省去字段选择

def addRecords(self,infos):
self.csr.executemany("insert into "+self.tabName+" values (?,?,?)",infos)
		print("record inserted successfully!")

可以这样调用

dh = DBHhelper("mydb1.db")
infos=((5,'Hanme',23),(1, 'Fornia', 6),    (2, 'Julier', 3),    (3, 'Susen', 4),    (4, 'Jaky', 2),    (5, 'Phinp', 3), (6, 'Sucy', 2), (7, 'Rose', 3) )
dh.addRecords(infos)


三、查询记录的参数化
1、列表查询

def getRecord(self,tabName):
		self.csr.execute("select * from "+tabName)
		records=self.csr.fetchall()
		if len(records)>0:
			return records

上面我们将查询所得的记录放入了一个列表中,那么我们调用就可以这样使用

dh = DBHhelper("mydb1.db")
record=dh.getRecord('customer')
for rd in record:
	print(rd[0],rd[1],rd[2])
dh.Dbclose()

输出结果则为:
Database mydb1.db created successfully!
table created successfully!
1 Paul 32
2 Mark 65
3 Luis 30
4 Kobb 24
5 Hanme 23
6 Fornia 61
7 Julier 31
8 Susen 42
9 Jaky 22
10 Phinp 32
11 Sucy 22
12 Rose 35

2、单条记录条件查询

	def getRecord(self,sname):
		self.csr.execute('select * from '+self.tabName+' where name=?', sname)
		print(self.csr.fetchone())  

我们还可以这样来给sql语句,将sname转换为列表

	def getRecord(self,sname):
		self.csr.execute('select * from '+self.tabName+' where name=?', [sname])
		print(self.csr.fetchone())  

3、多条记录条件查询

def queryRecords(self,sname):
		self.csr.execute('select * from '+self.tabName+' where name=?',[sname])
		records=self.csr.fetchall()
		print(len(records),"records be found")  
		return records

可以这样调用

dh = DBHhelper("mydb1.db")
qrs=dh.queryRecords('Julier')
for rd in qrs:
 	print(rd[0],rd[1],rd[2])

dh.Dbclose()


四、删除参数化
指定某个字段包涵特征输入

def delRecord(self,sname):
		self.csr.execute("delete from "+self.tabName+" where name=?",[sname])
		print(sname," deleted successfully!")

本篇博文将常见的python中sqlite需要用到的增删改查都一一做了介绍。


代码都在python3.8环境上运行测试通过的,可以直接使用。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/579899.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-11
下一篇 2022-04-11

发表评论

登录后才能评论

评论列表(0条)

保存