python的数据库接口标准是python db-api。大多数python数据库接口遵循这个标准。
可以为应用程序选择正确的数据库。python数据库api支持广泛的数据库服务器,如 -
以下是可用的python数据库接口 - python数据库接口和api的列表。需要为要访问的每种数据库下载一个单独的db api模块。 例如,如果需要访问oracle数据库和mysql数据库,则必须同时下载oracle和mysql数据库模块。
db api为尽可能使用python结构和语法处理数据库提供了最低标准。api包括以下内容:
python具有内置的sqlite支持。 在本节中,我们将学习使用mysql的相关概念和知识。 在早期python版本一般都使用mysqldb模块,但这个mysql的流行接口与python 3不兼容。因此,在教程中将使用pymysql模块。
pymysql是从python连接到mysql数据库服务器的接口。 它实现了python数据库api v2.0,并包含一个纯python的mysql客户端库。 pymysql的目标是成为mysqldb的替代品。
pymysql参考文档:http://pymysql.readthedocs.io/
在使用pymysql之前,请确保您的机器上安装了pymysql。只需在python脚本中输入以下内容即可执行它 -
#!/usr/bin/python3
import pymysql
在 windows 系统上,打开命令提示符 -
c:\users\administrator>python
python 3.6.1 (v3.6.1:69c0db5, mar 21 2017, 18:41:36) [msc v.1900 64 bit (amd64)] on win32
type "help", "copyright", "credits" or "license" for more information.
>>> import pymysql
traceback (most recent call last):
file "<stdin>", line 1, in <module>
modulenotfounderror: no module named 'pymysql'
>>>
如果产生如上结果,则表示pymysql
模块尚未安装。
最后一个稳定版本可以在pypi上使用,可以通过pip
命令来安装-
:\users\administrator> pip install pymysql
collecting pymysql
downloading pymysql-0.7.11-py2.py3-none-any.whl (78kb)
51% |████████████████▋ |
40kb 109kb/s eta 0:0 64% |████████████████████▊
| 51kb 112kb/s eta 77% |█████████████████████████ | 61kb 135kb/s 90% |█████████████████████████████
| 71kb 152 100% |████████████████████████████████| 81kb 163kb/s
installing collected packages: pymysql
successfully installed pymysql-0.7.11
c:\users\administrator>
或者(例如,如果pip不可用),可以从github下载tarball,并按照以下方式安装:
$ # x.x is the desired pymysql version (e.g. 0.5 or 0.6).
$ curl -l http://github.com/pymysql/pymysql/tarball/pymysql-x.x | tar xz
$ cd pymysql*
$ python setup.py install
$ # the folder pymysql* can be safely removed now.
注意 - 确保具有root权限来安装上述模块。
在连接到mysql数据库之前,请确保以下几点:
test
。test
中创建了一个表:employee
。employee
表格包含:fist_name
,last_name
,age
,sex
和income
字段。test
。创建表employee
的语句为:
create table `employee` (
`id` int(10) not null auto_increment,
`first_name` char(20) not null,
`last_name` char(20) default null,
`age` int(11) default null,
`sex` char(1) default null,
`income` float default null,
primary key (`id`)
) engine=innodb default charset=utf8;
实例
以下是python通过pymysql模块接口连接mysql数据库“test
”的示例 -
注意:在 windows 系统上,
import pymysql
和import pymysql
有区别。
#!/usr/bin/python3
#coding=utf-8
import pymysql
# open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute sql query using execute() method.
cursor.execute("select version()")
# fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("database version : %s " % data)
# disconnect from server
db.close()
运行此脚本时,会产生以下结果 -
database version : 5.7.14-log
如果使用数据源建立连接,则会返回连接对象并将其保存到db
中以供进一步使用,否则将db
设置为none
。 接下来,db
对象用于创建一个游标对象,用于执行sql查询。 最后,在结果打印出来之前,它确保数据库连接关闭并释放资源。
建立数据库连接后,可以使用创建的游标的execute
方法将数据库表或记录创建到数据库表中。
示例
下面演示如何在数据库:test
中创建一张数据库表:employee
-
#!/usr/bin/python3
#coding=utf-8
import pymysql
# open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# drop table if it already exist using execute() method.
cursor.execute("drop table if exists employee")
# create table as per requirement
sql = """create table `employee` (
`id` int(10) not null auto_increment,
`first_name` char(20) not null,
`last_name` char(20) default null,
`age` int(11) default null,
`sex` char(1) default null,
`income` float default null,
primary key (`id`)
) engine=innodb default charset=utf8;"""
cursor.execute(sql)
print("created table successfull.")
# disconnect from server
db.close()
运行此脚本时,会产生以下结果 -
created table successfull.
当要将记录创建到数据库表中时,需要执行insert
操作。
示例
以下示例执行sql的insert
语句以在employee
表中创建一条(多条)记录 -
#!/usr/bin/python3
#coding=utf-8
import pymysql
# open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# prepare sql query to insert a record into the database.
sql = """insert into employee(first_name,
last_name, age, sex, income)
values ('mac', 'su', 20, 'm', 5000)"""
try:
# execute the sql command
cursor.execute(sql)
# commit your changes in the database
db.commit()
except:
# rollback in case there is any error
db.rollback()
## 再次插入一条记录
# prepare sql query to insert a record into the database.
sql = """insert into employee(first_name,
last_name, age, sex, income)
values ('kobe', 'bryant', 40, 'm', 8000)"""
try:
# execute the sql command
cursor.execute(sql)
# commit your changes in the database
db.commit()
except:
# rollback in case there is any error
db.rollback()
print (sql)
print('yes, insert successfull.')
# disconnect from server
db.close()
运行此脚本时,会产生以下结果 -
yes, insert successfull.
上述插入示例可以写成如下动态创建sql查询 -
#!/usr/bin/python3
#coding=utf-8
import pymysql
# open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# prepare sql query to insert a record into the database.
sql = "insert into employee(first_name, \
last_name, age, sex, income) \
values ('%s', '%s', '%d', '%c', '%d' )" % \
('max', 'su', 25, 'f', 2800)
try:
# execute the sql command
cursor.execute(sql)
# commit your changes in the database
db.commit()
except:
# rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
示例
以下代码段是另一种执行方式,可以直接传递参数 -
..................................
user_id = "test123"
password = "password"
con.execute('insert into login values("%s", "%s")' % \
(user_id, password))
..................................
任何数据库上的读操作表示要从数据库中读取获取一些有用的信息。
在建立数据库连接后,就可以对此数据库进行查询了。 可以使用fetchone()
方法获取单条记录或fetchall()
方法从数据库表中获取多个值。
fetchone()
- 它获取查询结果集的下一行。 结果集是当使用游标对象来查询表时返回的对象。
fetchall()
- 它获取结果集中的所有行。 如果已经从结果集中提取了一些行,则从结果集中检索剩余的行。
rowcount
- 这是一个只读属性,并返回受execute()
方法影响的行数。
示例
以下过程查询employee
表中所有记录的工资超过1000
员工记录信息 -
#!/usr/bin/python3
#coding=utf-8
import pymysql
# open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# 按字典返回
# cursor = db.cursor(pymysql.cursors.dictcursor)
# prepare sql query to select a record from the table.
sql = "select * from employee \
where income > %d" % (1000)
#print (sql)
try:
# execute the sql command
cursor.execute(sql)
# fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
#print (row)
fname = row[1]
lname = row[2]
age = row[3]
sex = row[4]
income = row[5]
# now print fetched result
print ("name = %s %s,age = %s,sex = %s,income = %s" % \
(fname, lname, age, sex, income ))
except:
import traceback
traceback.print_exc()
print ("error: unable to fetch data")
# disconnect from server
db.close()
name = mac su,age = 20,sex = m,income = 5000.0
name = kobe bryant,age = 40,sex = m,income = 8000.0
update语句可对任何数据库中的数据进行更新操作,它可用于更新数据库中已有的一个或多个记录。
以下程序将所有sex
字段的值为“m
”的记录的年龄(age
字段)更新为增加一年。
#!/usr/bin/python3
#coding=utf-8
import pymysql
# open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
#cursor = db.cursor()
cursor = db.cursor(pymysql.cursors.dictcursor)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# prepare sql query to update required records
sql = "update employee set age = age + 1 \
where sex = '%c'" % ('m')
try:
# execute the sql command
cursor.execute(sql)
# commit your changes in the database
db.commit()
except:
# rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
当要从数据库中删除一些记录时,那么可以执行delete
操作。 以下是删除employee
中age
超过40
的所有记录的程序 -
#!/usr/bin/python3
#coding=utf-8
import pymysql
# open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# prepare sql query to delete required records
sql = "delete from employee where age > '%d'" % (40)
try:
# execute the sql command
cursor.execute(sql)
# commit your changes in the database
db.commit()
except:
# rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
事务是确保数据一致性的一种机制。事务具有以下四个属性 -
python db api 2.0提供了两种提交或回滚事务的方法。
示例
已经知道如何执行事务。 这是一个类似的例子 -
# prepare sql query to delete required records
sql = "delete from employee where age > '%d'" % (20)
try:
# execute the sql command
cursor.execute(sql)
# commit your changes in the database
db.commit()
except:
# rollback in case there is any error
db.rollback()
提交是一种操作,它向数据库发出信号以完成更改,并且在此操作之后,不会更改任何更改。
下面是一个简单的例子演示如何调用commit()
方法。
db.commit()
如果您对一个或多个更改不满意,并且要完全还原这些更改,请使用rollback()
方法。
下面是一个简单的例子演示如何调用rollback()
方法。
db.rollback()
要断开数据库连接,请使用close()
方法。
db.close()
如果用户使用close()
方法关闭与数据库的连接,则任何未完成的事务都将被数据库回滚。 但是,您的应用程序不会依赖于数据级别的实现细节,而是明确地调用提交或回滚。
错误有很多来源。一些示例是执行的sql语句中的语法错误,连接失败或为已取消或已完成语句句柄调用fetch
方法等等。
db api定义了每个数据库模块中必须存在的许多错误。下表列出了这些异常和错误 -
编号 | 异常 | 描述 |
---|---|---|
1 | warning | 用于非致命问题,是standarderror的子类。 |
2 | error | 错误的基类,是standarderror的子类。 |
3 | interfaceerror | 用于数据库模块中的错误,但不是数据库本身,是error的子类。 |
4 | databaseerror | 用于数据库中的错误,是error的子类。 |
5 | dataerror | databaseerror的子类引用数据中的错误。 |
6 | operationalerror | databaseerror的子类,涉及如丢失与数据库的连接等错误。 这些错误通常不在python脚本程序的控制之内。 |
7 | integrityerror | databaseerror 子类错误,可能会损害关系完整性,例如唯一性约束和外键。 |
8 | internalerror | databaseerror的子类,指的是数据库模块内部的错误,例如游标不再活动。 |
9 | programmingerror | databaseerror的子类,它引用错误,如错误的表名和其他安全。 |
10 | notsupportederror | databaseerror的子类,用于尝试调用不支持的功能。 |
python脚本应该处理这些错误,但在使用任何上述异常之前,请确保您的pymysql支持该异常。 可以通过阅读db api 2.0规范获得更多关于它们的信息。