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

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

在以往的博客中,我每次都不会忘记sqlite这个数据库,因为他小巧可爱,不需要安装任何服务,是个单纯的文件数据库,除此之外,还还可以很容易用于嵌入式开发,尤其基于小系统的linux。


所以在android里面也是大有用途。


我前面的博文分别介绍过如何在C#中QT中VC中,甚至还介绍了processing中如何调用sqlite。


这里,我们介绍python中如何调用sqlite,因为要写一个应用系统多少都要进行数据库的 *** 作。



一、创建数据库
在导入sqlite3后,创建两个对象connect和cursor(即链接和游标)之后,使用create语句即可创建一个数据库

	conn=sqlite3.connect("fistdb.db")
	csr=conn.cursor()
	csr.execute('''create table if not exists customer(ide int,name text,age int)''')


二、数据库的增删改查
数据表的增删改查是最常用的功能,这些功能都是采用sql语句来实现的,与其他平台没有任何差别,这里列出来插入和查询

csr.execute("insert into customer(ide, name, age) values (1, 'Paul', 32)")
csr.execute("select * from customer")


三、封装一个数据 *** 作的类
封装成类以后我们便于后面调用

import sqlite3




class DBHhelper(): 
	conn=sqlite3.connect("fistdb.db")
	csr=conn.cursor()
	def __init__(self):
		self.csr.execute('''create table if not exists customer(ide int,name text,age int)''')
		print("table created successfully!")

	def addRecord(self):
		self.csr.execute("insert into customer(ide, name, age) values (1, 'Paul', 32)")
		print("record inserted successfully!")

	def getRecord(self):
		self.csr.execute("select * from customer")
		for row in self.csr:
			print("ID = ", row[0])
			print("NAME = ", row[1])
			print("AGE = ", row[2])
	# def updateRecord(self):
	# def deleteRecord(self):	  
		
	def Dbclose(self):
		self.conn.commit()
		self.conn.close()



dh = DBHhelper()
dh.addRecord()
dh.getRecord()
dh.Dbclose()

运行上述代码,可以得到下面的输出
table created successfully!
ID = 1
NAME = Paul
AGE = 32


四、参数化类和方法
上面的类基本完成了对sqlite的封装,但感觉比较死,也就是说和外面没有交互。


我们知道,和外面交互的接口就是参数,所以我们要将类参数化,函数参数化。



1、类参数化
这里,我们要将数据的名称传入,就只能依靠它的构造函数__init__传参了。


class DBHhelper(): 
	conn=""
	csr=""
	def __init__(self,dbName):
		self.conn=sqlite3.connect(dbName)
		self.csr=self.conn.cursor()
		print("Database", dbName, " created successfully!")
		self.csr.execute('''create table if not exists customer(ide int,name text,age int)''')
		print("table created successfully!")

	def addRecord(self):
		self.csr.execute("insert into customer(ide, name, age) values (1, 'Paul', 32)")
		print("record inserted successfully!")

	def getRecord(self):
		self.csr.execute("select * from customer")
		for row in self.csr:
			print("ID = ", row[0])
			print("NAME = ", row[1])
			print("AGE = ", row[2])
	# def updateRecord(self):
	# def deleteRecord(self):	  
		
	def Dbclose(self):
		self.conn.commit()
		self.conn.close()



dh = DBHhelper("mydb1.db")
dh.addRecord()
dh.getRecord()
dh.Dbclose()

运行结果
Database mydb1.db created successfully!
table created successfully!
record inserted successfully!
ID = 1
NAME = Paul
AGE = 32

2、函数参数化
函数的参数化,涉及的参数比较多,尤其涉及到的字段比较多,而且灵活度也是需要考虑的,所以,我们专门用一篇博文来完成函数的参数化。


请继续关注

请参看《python中sqlite的基本调用和数据库类的封装案例(2)》

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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存