以SQLite和PySqlite为例来学习Python DB API
作者:mdxy-dxy 发布时间:2023-07-13 02:19:14
Python应用编程需要用到的针对不同数据库引擎的数据库接口:http://wiki.python.org/moin/DatabaseInterfaces
Python标准的DB API 2.0见:http://www.python.org/dev/peps/pep-0249/
本文将以SQLite和PySqlite为例来学习Python DB API。
pysqlite是一个sqlite为python 提供的api接口,它让一切对于sqlit的操作都变得异常简单。
从Python2.5起,pysqlite作为Python的一个标准模块。在使用标准库时,它被简称为sqlite3模块。
sqlite3标准库,详见:http://docs.python.org/3.3/library/sqlite3.html
基本的学习内容如下:
1.创建一张表
# filename:create.py
import sqlite3
# 创建连接对象
conn = sqlite3.connect('E:/code/py/db/test.db')
# 创建一个游标对象
cur = conn.cursor()
# 创建数据表的sql语句
createtb_sql = """create table test(
id integer,
name text,
age integer);"""
# 调用execute()执行create_sql语句
cur.execute(createtb_sql)
# 关闭游标
cur.close()
# 关闭连接
conn.close()
2.简单的插入数据
# filename:insert.py
import sqlite3
# 创建连接对象
conn = sqlite3.connect('E:/code/py/db/test.db')
# 创建一个游标对象
cur = conn.cursor()
# 向数据表中插入数据的sql语句
'''
insert_sql = """
insert into test values(1, 'huhu', 20);
insert into test values(2, 'hengheng', 18);
insert into test values(3, 'huahua', 18);
"""
'''
insert_sql = """
insert into test values(1, 'huhu', 20);
"""
# 调用execute()执行insert sql语句
# execute一次只能执行一条语句
cur.execute(insert_sql)
# 提交事务
conn.commit()
# 关闭游标
cur.close()
# 关闭连接
conn.close()
3.查询
# filename:select.py
import sqlite3
# 创建连接对象
conn = sqlite3.connect('E:/code/py/db/test.db')
# 创建一个游标对象
cur = conn.cursor()
# 查询数据表的sql语句
select_sql = """ select * from test;"""
# 调用execute()执行select sql语句
cur.execute(select_sql)
'''
while True:
# fetchone()把查询的结果集的下一行作为序列或者None
row = cur.fetchone()
if row == None:
break
print(row)
'''
'''
# fetchall()把查询的结果集的所有行作为序列的序列
for row in cur.fetchall():
print(row)
'''
# 迭代对象遍历
for row in cur:
print(row)
# 关闭游标
cur.close()
# 关闭连接
conn.close()
4.删除数据
# filename:delete.py
import sqlite3
# 创建连接对象
conn = sqlite3.connect('E:/code/py/db/test.db')
# 创建一个游标对象
cur = conn.cursor()
# delete语句
delete_sql = """delete from test"""
# execute()执行sql语句
cur.execute(delete_sql)
# commit()提交事务
conn.commit()
# 关闭游标
cur.close()
# 关闭连接
conn.close()
以上四步的运行结果:
5.一次插入多条数据
# filename:insertmany.py
import sqlite3
# 创建连接对象
conn = sqlite3.connect('E:/code/py/db/test.db')
# 创建一个游标对象
cur = conn.cursor()
# 向数据表中插入数据的sql语句
insert_sql = """insert into test values(?, ?, ?)"""
# 调用execute()执行insert sql语句
# execute一次只能执行一条语句
for line in open('E:/code/py/db/data.txt'):
fields = line.split(',')
vals = [f for f in fields]
cur.execute(insert_sql,vals)
# 提交事务
conn.commit()
# 关闭游标
cur.close()
# 关闭连接
conn.close()
data.txt:
1,huhu,18
2,hengheng,18
3,lq,20
运行结果:
6.插入数据的方法(参数绑定,executemany的使用):
# inserts.py
import sqlite3
# 创建连接对象
conn = sqlite3.connect('E:/code/py/db/test.db')
# 创建一个游标对象
cur = conn.cursor()
# 向数据表中插入数据的sql语句
# 最简单的insert形式
insert_sql1 = """insert into test values(1, 'huhu', 20);"""
# execute()一次只能执行一条语句
cur.execute(insert_sql1)
# 参数绑定
# execute()第二个参数:位置参数或者字典类型参数
insert_sql2 = """insert into test values(?, ?, ?)"""
cur.execute(insert_sql2, (2,'hengheng',18))
insert_sql3 = """insert into test values(:id, :name, :age)"""
cur.execute(insert_sql3, {'id':3, 'name':'lq', 'age':18})
# executemany()第二个参数:列表类型参数,适用于迭代器和生成器
l = [(4, 'huhu', 18), (5, 'hh', 18), (6, 'lq', 18)]
cur.executemany(insert_sql2, l)
# 利用生成器实现
def l_generator():
l = [(7, 'huhu', 18), (8, 'hh', 18), (9, 'lq', 18)]
for t in l:
yield(t)
cur.executemany(insert_sql2, l_generator())
# 提交事务
conn.commit()
# 关闭游标
cur.close()
# 关闭连接
conn.close()
运行结果:
7.带条件的的update、delelte和select语句
(1)update
# filename:update.py
import sqlite3
# 创建连接对象
conn = sqlite3.connect('E:/code/py/db/test.db')
# 创建一个游标对象
cur = conn.cursor()
# update语句
update_sql = """update test set name = 'noname' where id = ?"""
# execute()和executem()执行sql语句
x = (1, )
cur.execute(update_sql, x)
y = (2, )
cur.execute(update_sql, y)
l = [(3, ),(4, ),(5, )]
cur.executemany(update_sql, l)
# commit()提交事务
conn.commit()
# 关闭游标
cur.close()
# 关闭连接
conn.close()
运行结果:
(2)delete
# filename:delete1.py
import sqlite3
# 创建连接对象
conn = sqlite3.connect('E:/code/py/db/test.db')
# 创建一个游标对象
cur = conn.cursor()
# delete语句
delete_sql = """delete from test where id = ?"""
# execute()和executemany()执行sql语句
cur.execute(delete_sql, (1, ))
cur.executemany(delete_sql, [(2, ), (3, )])
# commit()提交事务
conn.commit()
# 关闭游标
cur.close()
# 关闭连接
conn.close()
运行结果:
(3)select
# filename:select1.py
import sqlite3
# 创建连接对象
conn = sqlite3.connect('E:/code/py/db/test.db')
# 创建一个游标对象
cur = conn.cursor()
# 查询数据表的sql语句
select_sql = """ select * from test where id = ?;"""
# 调用execute()执行select sql语句
x = (8, )
cur.execute(select_sql, x)
'''
# 在executemany中,不能执行select语句
y = [(2, ), (3, )]
cur.executemany(select_sql, y)
'''
# 迭代对象遍历
for row in cur:
print(row)
# 关闭游标
cur.close()
# 关闭连接
conn.close()
运行结果:
sqlite3标准库相比Python DB API 2.0,增加了一个较为方便的函数executescript函数(一次可以执行多条sql),介绍如下:
This is a nonstandard convenience method for executing multiple SQL statements at once. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter.
sql_script can be an instance of str or bytes.
Example:
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
create table person(
firstname,
lastname,
age
);
create table book(
title,
author,
published
);
insert into book(title, author, published)
values (
'Dirk Gently''s Holistic Detective Agency',
'Douglas Adams',
);
""")
好了这篇文章就为大家介绍到这了,希望大家以后多多支持。
来源:https://www.cnblogs.com/fortwo/archive/2013/04/22/3035691.html


猜你喜欢
- 前言接口在软件工程扮演重要角色,随着应用程序的功能不断扩展,代码库的更新和改变也难以管理。在许多情况下,会发现有一些看起来非常相似,但却不相
- 我们都知道并发(不是并行)编程目前有四种方式,多进程,多线程,异步,和协程。多进程编程在python中有类似C的os.fork,当然还有更高
- 客户的一台服务器出现Raid故障,经过我们的努力,数据基本恢复成功,但是其中的一个SQL Server日志文件(扩展名LDF)损坏严重,基本
- 一、MYSQL的索引索引(Index):帮助Mysql高效获取数据的一种数据结构。用于提高查找效率,可以比作字典。可以简单理解为排好序的快速
- 命令行方式运行Python脚本在这个章节中,我们将写一些简单的数据库管理脚本。在此之前让我们来复习一下如何通过命令行方式执行Py
- 文字链接可以说是网页中最常见的页面元素了,默认的文字链接样式都是带下划线的效果,这种一陈不变的外观可能使很多朋友都想改变它,以使之符合页面的
- go-cqhttp安装一、 简介1、 介绍官方文档地址:https://docs.go-cqhttp.org/各种框架都只是机器人的各种实现
- fixtures调用其他fixtures及fixture复用性 pytest最大的优点之一就是它非常灵活。它可以将复杂的测试需求简
- 自从jQuery搞出特性侦探这东东,西方从来没有如此狂热研究浏览器。在以前javascript与DOM遍地是bug,美工主宰前端的年代,人们
- prop与$emit的用法1.vue组件Prop传递数据 组件实例的作用域是孤立的,这意味着不能在子组件的模板内直接引父组件的数据
- 昨天在网上找资料的时间无意进了一个站,糊里糊涂就进去了,想提权提不起来,后来加上服务商的Q号想社工一下,射了半天得知服务器的安全是绿盟的人给
- golang中list包用法可以参看这篇文章但是list包中大部分对于e *Element进行操作的元素都可能会导致程序崩溃,其根本原因是e
- 1.今天在看JavaScript学习指南的时候做的课后习题,也因此详细的对函数的传入参数进行比较深入的研究.题目如下:函数如何才能修改其作用
- phpMyAdmin可以管理整个MySQL服务器(需要超级用户),也可以管理单个数据库。为了实现后一种,你将需要合理设置MySQL用户,他只
- 从一个字符串开始在CODE上查看代码片派生到我的代码片 >>>time_str='2008-08-08
- 前言最近学完Python,写了几个爬虫练练手,网上的教程有很多,但是有的已经不能爬了,主要是网站经常改,可是爬虫还是有通用的思路的,即下载数
- webpack代码拆分webpack有两种组织模块依赖的方式,同步和异步。异步依赖作为分割点,形成一个新的块,在优化了依赖树后,每一个异步区
- help函数是python的一个内置函数(python的内置函数可以直接调用,无需import),它是python自带的函数,任何时候都可以
- 前言因为NLP作业需要用到kenlm,而kenlm在linux下更为方便。本人win10之前开启了子系统,所以就打算在子系统下进行相关作业的
- 用户体验(User Experience,简称UE)是用户在使用产品过程中建立起来的一种纯主观感受。在基于Web的产品设计中,UE是一个相对