python sqlite3 MySQLdb
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时,只要搞清楚Connection
和Cursor
对象,打开后一定记得关闭,就可以放心地使用。
使用Cursor
对象执行insert
,update
,delete
语句时,执行结果由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
- import MySQLdb
- conn=MySQLdb.connect(db='mydb',host='myhost',user='u',passwd='p')
- cur = conn.cursor()
- cur.execute('show databases;')
- for data in cur.fetchall():
- print data
- cur.close()
- conn.close()
python sqlite3 MySQLdb的更多相关文章
- python sqlite3使用
python sqlite3文档地址:http://docs.python.org/2/library/sqlite3.html The sqlite3 module was written by G ...
- Python的MySQLdb模块安装,连接,操作,增删改
1. 首先确认python的版本为2.3.4以上,如果不是需要升级python的版本 python -V 检查python版本 2. 安装mysql, 比如安装在/usr/local/my ...
- Ubuntu安装MySQL和Python库MySQLdb步骤
一.安装MySQL服务器和客户端 执行以下命令: sudo apt-get install mysql-server-5.6 mysql-client-5.6 sudo apt-get install ...
- python之mysqldb模块安装
之所以会写下这篇日志,是因为安装的过程有点虐心.目前这篇文章是针对windows操作系统上的mysqldb的安装.安装python的mysqldb模块,首先当然是找一些官方的网站去下载:https:/ ...
- python sqlite3 数据库操作
python sqlite3 数据库操作 SQLite3是python的内置模块,是一款非常小巧的嵌入式开源数据库软件. 1. 导入Python SQLite数据库模块 import sqlite3 ...
- Python MySQL(MySQLdb)
From: http://www.yiibai.com/python/python_mysql.html Python标准的数据库接口的Python DB-API(包括Python操作MySQL).大 ...
- python sqlite3 入门 (视频讲座)
python sqlite3 入门 (视频讲座) an SQLite mini-series! - Simple Databases with Python 播放列表: YouTube https:/ ...
- windows(32位 64位)下python安装mysqldb模块
windows(32位 64位)下python安装mysqldb模块 www.111cn.net 编辑:mengchu9 来源:转载 本文章来给各位使用在此windows系统中的python来安装一个 ...
- Python用MySQLdb, pymssql 模块通过sshtunnel连接远程数据库
转载自 https://www.cnblogs.com/luyingfeng/p/6386093.html 安全起见,数据库的访问多半是要做限制的,所以就有一个直接的问题是,往往多数时候,在别的机器上 ...
随机推荐
- Sublime Text3 注册码激活码(持续更新中2018-11-20)
Sublime Text 3的注册码 个人记录,便于查找 谢谢各位的认可 11.20版本 ----- BEGIN LICENSE ----- sgbteam Single User License E ...
- oracle odbc 驱动安装(不安装oracle客户端)
1.下载odbc驱动 需要下载两个东西 instantclient-basiclite-nt-12.1.0.1.0.zip instantclient-odbc-nt-12.1.0.1.0.zip 由 ...
- 【GDI+】MFC画图- 消除锯齿(转)
原文转自 https://wenku.baidu.com/view/b5460979700abb68a982fbcf.html 在常规条件下,MFC画出来的图形.文字都是有锯齿的.如下图所示: 怎样才 ...
- ui_modules和ui_method
## 06ui.py #coding:utf-8 import tornado.httpserver import tornado.ioloop import tornado.options impo ...
- Xcode5 上64位编译 出错No architectures to compile for
http://blog.csdn.net/chocolateloveme/article/details/16900999 详细错误信息如下: No architectures to compile ...
- UVA 10803 Thunder Mountain
纠结在这句话了If it is impossible to get from some town to some other town, print "Send Kurdy" in ...
- 恢复安装过树莓派相关操作系统的TF卡容量
原文地址:传送门 前言玩树莓派的都知道,当我们向TF卡写入系统后,在Windows下能识别的只有几百M的容量了,这主要是由于在装Linux系统的时候给TF卡分了Windows无法识别的分区,下面我用图 ...
- thinkphp函数学习(2)——microtime, memory_get_usage, dirname, strtolower, is_file
1. microtime() 返回 微秒 秒 这种格式的内容 例子 <?php echo(microtime()); ?> 输出: 0.25139300 1138197510 // 前 ...
- CSS,HTML页面定制
/*simplememory*/ #google_ad_c1, #google_ad_c2 {display:none;} .syntaxhighlighter a, .syntaxhighlight ...
- 洛谷——P1579 哥德巴赫猜想(升级版)
P1579 哥德巴赫猜想(升级版) 题目背景 1742年6月7日哥德巴赫写信给当时的大数学家欧拉,正式提出了以下的猜想:任何一个大于9的奇数都可以表示成3个质数之和.质数是指除了1和本身之外没有其他约 ...