使用Python对SQLite数据库操作

yipeiwu_com6年前Python基础

SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在IOS和Android的APP中都可以集成。

Python内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。

在使用SQLite前,我们先要搞清楚几个概念:

表是数据库中存放关系数据的集合,一个数据库里面通常都包含多个表,比如学生的表,班级的表,学校的表,等等。表和表之间通过外键关联。

要操作关系数据库,首先要连接到数据库,一个数据库连接称为Connection。

连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句,然后,获得执行结果。

一、连接数据库

import sqlite3
#数据库名
db_name = "test.db"
#表名
table_name = "catalog"
conn = sqlite3.connect(db_name)

二、打开游标

rs = conn.cursor()

三、建表

sql = 'create table ' + table_name + ' (id varchar(20) primary key, pid integer, name varchar(10))'
try:
 rs.execute(sql)
 print("建表成功")
except:
 print("建表失败")

四、增,删,改,查操作

# 增:增加三条记录
sql = "Insert into " + table_name + " values ('001', 1, '张三')"
try:
 rs.execute(sql)
 #提交事务
 conn.commit()
 print("插入成功")
except:
 print("插入失败")
sql = "Insert into " + table_name + " values ('002', 2, '李四')"
try:
 rs.execute(sql)
 #提交事务
 conn.commit()
 print("插入成功")
except:
 print("插入失败")
sql = "Insert into " + table_name + " values ('003', 3, '王五')"
try:
 rs.execute(sql)
 #提交事务
 conn.commit()
 print("插入成功")
except:
 print("插入失败")
# 删:删除pid等于3的记录
sql = "Delete from " + table_name + " where pid = 3"
try:
 rs.execute(sql)
 conn.commit()
 print("删除成功")
except:
 print("删除失败")
# 改:将pid等于2的记录的pid改为1
sql = "Update " + table_name + " set pid = 1 where pid = 2"
try:
 rs.execute(sql)
 conn.commit()
 print("修改成功")
except:
 print("修改失败")
# 查
# 查询数据库中所有表名
sql = "Select name From sqlite_master where type = 'table'"
res = rs.execute(sql)
print(res.fetchall())
# 查询表中所有记录
sql = "Select * from " + table_name
try: 
 res = rs.execute(sql)
 print(res.fetchall())
except:
 print([])

五、关闭游标

rs.close()

六、关闭数据库连接

conn.close()

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持【听图阁-专注于Python设计】!

相关文章

python发送多人邮件没有展示收件人问题的解决方法

背景: 工作过程中需要对现有的机器、服务做监控,当服务出现问题后,邮件通知对应的人 问题: 使用python 2.7自带的email库来进行邮件的发送,但是发送后没有展示收件人列表内容...

在Python中过滤Windows文件名中的非法字符方法

网上有三种写法: 第一种(所有非法字符都不转义): def setFileTitle(self,title): fileName = re.sub('[\/:*&#...

Python闭包执行时值的传递方式实例分析

本文实例分析了Python闭包执行时值的传递方式。分享给大家供大家参考,具体如下: 代码中有问题和问题的解释。 #!/usr/bin/python #coding: utf-8 #...

Pytorch基本变量类型FloatTensor与Variable用法

Pytorch基本变量类型FloatTensor与Variable用法

pytorch中基本的变量类型当属FloatTensor(以下都用floattensor),而Variable(以下都用variable)是floattensor的封装,除了包含floa...

基于DataFrame筛选数据与loc的用法详解

DataFrame筛选数据与loc用法 python中pandas下的DataFrame是一个很不错的数据结构,附带了许多操作、运算、统计等功能。 如何从一个DataFrame中筛选中出...