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

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

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

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

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

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

Python定义了一套操作数据库的API接口,任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可。

由于SQLite的驱动内置在Python标准库中,所以我们可以直接来操作SQLite数据库。

我们在Python交互式命令行实践一下:

# 导入SQLite驱动:
>>> import sqlite3
# 连接到SQLite数据库
# 数据库文件是test.db
# 如果文件不存在,会自动在当前目录创建:
>>> conn = sqlite3.connect('test.db')
# 创建一个Cursor:
>>> cursor = conn.cursor()
# 执行一条SQL语句,创建user表:
>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
<sqlite3.Cursor object at 0x10f8aa260>
# 继续执行一条SQL语句,插入一条记录:
>>> cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')
<sqlite3.Cursor object at 0x10f8aa260>
# 通过rowcount获得插入的行数:
>>> cursor.rowcount
1
# 关闭Cursor:
>>> cursor.close()
# 提交事务:
>>> conn.commit()
# 关闭Connection:
>>> conn.close()

我们再试试查询记录:

>>> conn = sqlite3.connect('test.db')
>>> cursor = conn.cursor()
# 执行查询语句:
>>> cursor.execute('select * from user where id=?', ('1',))
<sqlite3.Cursor object at 0x10f8aa340>
# 获得查询结果集:
>>> values = cursor.fetchall()
>>> values
[('1', 'Michael')]
>>> cursor.close()
>>> conn.close()

使用Python的DB-API时,只要搞清楚ConnectionCursor对象,打开后一定记得关闭,就可以放心地使用。

使用Cursor对象执行insertupdatedelete语句时,执行结果由rowcount返回影响的行数,就可以拿到执行结果。

使用Cursor对象执行select语句时,通过featchall()可以拿到结果集。结果集是一个list,每个元素都是一个tuple,对应一行记录。

如果SQL语句带有参数,那么需要把参数按照位置传递给execute()方法,有几个?占位符就必须对应几个参数,例如:

cursor.execute('select * from user where name=? and pwd=?', ('abc', 'password'))

SQLite支持常见的标准SQL语句以及几种常见的数据类型。具体文档请参阅SQLite官方网站。

小结

在Python中操作数据库时,要先导入数据库对应的驱动,然后,通过Connection对象和Cursor对象操作数据。

要确保打开的Connection对象和Cursor对象都正确地被关闭,否则,资源就会泄露。

如何才能确保出错的情况下也关闭掉Connection对象和Cursor对象呢?请回忆try:...except:...finally:...的用法。

练习

请编写函数,在Sqlite中根据分数段查找指定的名字:

# -*- coding: utf-8 -*-

import os, sqlite3

db_file = os.path.join(os.path.dirname(__file__), 'test.db')
if os.path.isfile(db_file):
os.remove(db_file) # 初始数据:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)')
cursor.execute(r"insert into user values ('A-001', 'Adam', 95)")
cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")
cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")
cursor.close()
conn.commit()
conn.close() def get_score_in(low, high):
' 返回指定分数区间的名字,按分数从低到高排序 '
# 测试:
assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95)
assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80)
assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100) print('Pass') MySQLDB下载地址:http://www.codegood.com/downloads
  1. import MySQLdb
  2. conn=MySQLdb.connect(db='mydb',host='myhost',user='u',passwd='p')
  3. cur = conn.cursor()
  4. cur.execute('show databases;')
  5. for data in cur.fetchall():
  6. print data
  7. cur.close()
  8. conn.close()
												

python sqlite3 MySQLdb的更多相关文章

  1. python sqlite3使用

    python sqlite3文档地址:http://docs.python.org/2/library/sqlite3.html The sqlite3 module was written by G ...

  2. Python的MySQLdb模块安装,连接,操作,增删改

    1. 首先确认python的版本为2.3.4以上,如果不是需要升级python的版本     python -V   检查python版本 2. 安装mysql, 比如安装在/usr/local/my ...

  3. Ubuntu安装MySQL和Python库MySQLdb步骤

    一.安装MySQL服务器和客户端 执行以下命令: sudo apt-get install mysql-server-5.6 mysql-client-5.6 sudo apt-get install ...

  4. python之mysqldb模块安装

    之所以会写下这篇日志,是因为安装的过程有点虐心.目前这篇文章是针对windows操作系统上的mysqldb的安装.安装python的mysqldb模块,首先当然是找一些官方的网站去下载:https:/ ...

  5. python sqlite3 数据库操作

    python sqlite3 数据库操作 SQLite3是python的内置模块,是一款非常小巧的嵌入式开源数据库软件. 1. 导入Python SQLite数据库模块 import sqlite3 ...

  6. Python MySQL(MySQLdb)

    From: http://www.yiibai.com/python/python_mysql.html Python标准的数据库接口的Python DB-API(包括Python操作MySQL).大 ...

  7. python sqlite3 入门 (视频讲座)

    python sqlite3 入门 (视频讲座) an SQLite mini-series! - Simple Databases with Python 播放列表: YouTube https:/ ...

  8. windows(32位 64位)下python安装mysqldb模块

    windows(32位 64位)下python安装mysqldb模块 www.111cn.net 编辑:mengchu9 来源:转载 本文章来给各位使用在此windows系统中的python来安装一个 ...

  9. Python用MySQLdb, pymssql 模块通过sshtunnel连接远程数据库

    转载自 https://www.cnblogs.com/luyingfeng/p/6386093.html 安全起见,数据库的访问多半是要做限制的,所以就有一个直接的问题是,往往多数时候,在别的机器上 ...

随机推荐

  1. 学习webservice

    客户端测试页: WebService代码: using System; using System.Collections.Generic; using System.Linq; using Syste ...

  2. 实现自己的系统调用针对linux-2.6.34【转】

    转自:http://biancheng.dnbcw.net/linux/303362.html 在linux下实现自己的系统调用.主要功能是:遍历系统的进程,并将相关的进程信息存放在自己定义的结构体中 ...

  3. linux free 命令 ,讲解得比较好

    解释一下Linux上free命令的输出. 下面是free的运行结果,一共有4行.为了方便说明,我加上了列号.这样可以把free的输出看成一个二维数组FO(Free Output).例如: FO[2][ ...

  4. int与Integer区别+Integer类详解

    //Integer范围-128~127 //Integer与Integer比较 Integer a_127 = 127; Integer b_127 = 127; Integer c_new_127 ...

  5. Codeforces Round #446 (Div. 2) C. Pride【】

    C. Pride time limit per test 2 seconds memory limit per test 256 megabytes input standard input outp ...

  6. Hadoop之Vmware通过仅Use Host-Only networking(使用主机网络)主机链接

    Use Host-Only networking(使用主机网络)连接方式 [1]现在宿主机也就是本地电脑上设置IP地址 [2]设置虚拟机 Host-Only 方式            验证    宿 ...

  7. Python的工具包[0] -> numpy科学计算 -> numpy 库及使用总结

    NumPy 目录 关于 numpy numpy 库 numpy 基本操作 numpy 复制操作 numpy 计算 numpy 常用函数 1 关于numpy / About numpy NumPy系统是 ...

  8. Java-静态代码块,构造代码块,构造函数

    静态代码块:用staitc声明,jvm加载类时执行,仅执行一次 构造代码块:类中直接用{}定义,每一次创建对象时执行. 执行顺序优先级:静态块, main(),函数,构造块,构造方法. 构造函数 pu ...

  9. 磁盘镜像工具Guymager

    磁盘镜像工具Guymager   在数字取证中,经常需要对磁盘制作镜像,以便于后期分析.Kali Linux提供一款轻量级的磁盘镜像工具Guymager.该工具采用图形界面化方式,提供磁盘镜像和磁盘克 ...

  10. nginx的proxy_set_header

    nginx配置的server段: listen 8888; server_name wyc.com; location /user { proxy_set_header HOST fake.com; ...