python中sqlite的基本调用和数据库类的封装案例(1)
  TEZNKK3IfmPf 2023年11月14日 54 0

在以往的博客中,我每次都不会忘记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)》

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
TEZNKK3IfmPf