以SQLite和PySqlite为例来学习Python DB API

所属分类: 脚本专栏 / python 阅读数: 412
收藏 0 赞 0 分享

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',
  );
  """)

好了这篇文章就为大家介绍到这了,希望大家以后多多支持脚本之家。

更多精彩内容其他人还在看

Python实现按学生年龄排序的实际问题详解

这篇文章主要给大家介绍了关于Python实现按学生年龄排序实际问题的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。
收藏 0 赞 0 分享

Python开发的HTTP库requests详解

Requests是用Python语言编写,基于urllib,采用Apache2 Licensed开源协议的HTTP库。它比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求。Requests的哲学是以PEP 20 的习语为中心开发的,所以它比urllib更加P
收藏 0 赞 0 分享

Python网络爬虫与信息提取(实例讲解)

下面小编就为大家带来一篇Python网络爬虫与信息提取(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

在python3环境下的Django中使用MySQL数据库的实例

下面小编就为大家带来一篇在python3环境下的Django中使用MySQL数据库的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Python 3.x读写csv文件中数字的方法示例

在我们日常开发中经常需要对csv文件进行读写,下面这篇文章主要给大家介绍了关于Python 3.x读写csv文件中数字的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。
收藏 0 赞 0 分享

Python实现解析Bit Torrent种子文件内容的方法

这篇文章主要介绍了Python实现解析Bit Torrent种子文件内容的方法,结合实例形式分析了Python针对Torrent文件的读取与解析相关操作技巧与注意事项,需要的朋友可以参考下
收藏 0 赞 0 分享

Python实现文件内容批量追加的方法示例

这篇文章主要介绍了Python实现文件内容批量追加的方法,结合实例形式分析了Python文件的读写相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python简单实现自动删除目录下空文件夹的方法

这篇文章主要介绍了Python简单实现自动删除目录下空文件夹的方法,涉及Python针对文件与目录的读取、判断、删除等相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

简单学习Python多进程Multiprocessing

这篇文章主要和大家一起简单的学习Python多进程Multiprocessing ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Python导入模块时遇到的错误分析

这篇文章主要给大家详细解释了在Python处理导入模块的时候出现错误以及具体的情况分析,非常的详尽,有需要的小伙伴可以参考下
收藏 0 赞 0 分享
查看更多