登录
首页精彩阅读在Python程序中操作MySQL的基本方法
在Python程序中操作MySQL的基本方法
2018-08-01
收藏

在Python程序中操作MySQL的基本方法

最近在学习python,这种脚本语言毫无疑问的会跟数据库产生关联,因此这里介绍一下如何使用python操作mysql数据库。我python也是零基础学起,所以本篇博客针对的是python初学者,大牛可以选择绕道。
另外,本篇基于的环境是Ubuntu13.10,使用的python版本是2.7.5。
MYSQL数据库
MYSQL是一个全球领先的开源数据库管理系统。它是一个支持多用户、多线程的数据库管理系统,与Apache、PHP、Linux共同组成LAMP平台,在web应用中广泛使用,例如Wikipedia和YouTube。MYSQL包含两个版本:服务器系统和嵌入式系统。
环境配置

在我们开始语法学习之前,还需要按装mysqlpythonmysql操作的模块。

安装mysql:    
sudo apt-get install mysql-server

安装过程中会提示你输入root帐号的密码,符合密码规范即可。

接下来,需要安装pythonmysql的操作模块:    
sudo apt-get install python-mysqldb

这里需要注意:安装完python-mysqldb之后,我们默认安装了两个python操作模块,分别是支持C语言API的_mysql和支持Python API的MYSQLdb。稍后会重点讲解MYSQLdb模块的使用。

接下来,我们进入MYSQL,创建一个测试数据库叫testdb。创建命令为:    
create database testdb;
然后,我们创建一个测试账户来操作这个testdb数据库,创建和授权命令如下:    
create user 'testuser'@'127.0.0.1' identified by 'test123';
grant all privileges on testdb.* to 'testuser'@'127.0.0.1';
 
_mysql module

_mysql模块直接封装了MYSQL的C语言API函数,它与python标准的数据库API接口是不兼容的。我更推荐大家使用面向对象的MYSQLdb模块才操作mysql,这里只给出一个使用_mysql模块的例子,这个模块不是我们学习的重点,我们只需要了解有这个模块就好了。    
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import _mysql
import sys
 
try:
 con = _mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb')
 con.query("SELECT VERSION()")
 result = con.use_result()
 
 print "MYSQL version : %s " % result.fetch_row()[0]
 
except _mysql.Error, e:
 print "Error %d: %s %s" % (e.args[0], e.args[1])
 sys.exit(1)
 
finally:
 if con:
  con.close()

这个代码主要是获取当前mysql的版本,大家可以模拟敲一下这部分代码然后运行一下。
MYSQLdb module

MYSQLdb是在_mysql模块的基础上进一步进行封装,并且与python标准数据库API接口兼容,这使得代码更容易被移植。Python更推荐使用这个MYSQLdb模块来进行MYSQL操作。    
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import MySQLdb as mysql
 
try:
 conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb')
 cur = conn.cursor()
 cur.execute("SELECT VERSION()")
 
 version = cur.fetchone()
 print "Database version : %s" % version
 
except mysql.Error, e:
 print "Error %d:%s" % (e.args[0], e.args[1])
 exit(1)
 
finally:
 if conn:
  conn.close()


我们导入了MySQLdb模块并把它重命名为mysql,然后调用MySQLdb模块的提供的API方法来操作数据库。同样也是获取当前主机的安装的mysql版本号。
创建新表

接下来,我们通过MySQLdb模块创建一个表,并在其中填充部分数据。实现代码如下:
    
#!/usr/bin/python
 
# -*- coding: utf-8 -*-
 
import MySQLdb as mysql
 
conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb');
 
with conn:
 cur = conn.cursor()
 cur.execute("DROP TABLE IF EXISTS writers");
 cur.execute("CREATE TABLE writers(id INT PRIMARY KEY AUTO_INCREMENT, name varchar(25))")
 cur.execute("insert into writers(name) values('wangzhengyi')")
 cur.execute("insert into writers(name) values('bululu')")
 cur.execute("insert into writers(name) values('chenshan')")

这里使用了with语句。with语句会执行conn对象的enter()和__exit()方法,省去了自己写try/catch/finally了。

执行完成后,我们可以通过mysql-client客户端查看是否插入成功,查询语句:    
select * from writers;

查询结果如下:

查询数据
刚才往表里插入了部分数据,接下来,我们从表中取出插入的数据,代码如下:    
#!/usr/bin/python
 
import MySQLdb as mysql
 
conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb');
 
with conn:
 cursor = conn.cursor()
 cursor.execute("select * from writers")
 rows = cursor.fetchall()
 
 for row in rows:
  print row

查询结果如下:
    
(1L, 'wangzhengyi')
(2L, 'bululu')
(3L, 'chenshan')

dictionary cursor

我们刚才不论是创建数据库还是查询数据库,都用到了cursor。在MySQLdb模块有许多种cursor类型,默认的cursor是以元组的元组形式返回数据的。当我们使用dictionary cursor时,数据是以python字典形式返回的。这样我们就可以通过列名获取查询数据了。

还是刚才查询数据的代码,改为dictionary cursor只需要修改一行代码即可,如下所示:    
#!/usr/bin/python
 
import MySQLdb as mysql
 
conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb');
 
with conn:
 cursor = conn.cursor(mysql.cursors.DictCursor)
 cursor.execute("select * from writers")
 rows = cursor.fetchall()
 
 for row in rows:
  print "id is %s, name is %s" % (row['id'], row['name'])

使用dictionary cursor,查询结果如下:    
id is 1, name is wangzhengyi
id is 2, name is bululu
id is 3, name is chenshan
预编译
之前写过php的同学应该对预编译很了解,预编译可以帮助我们防止sql注入等web攻击还能帮助提高性能。当然,python肯定也是支持预编译的。预编译的实现也比较简单,就是用%等占位符来替换真正的变量。例如查询id为3的用户的信息,使用预编译的代码如下:    
#!/usr/bin/python
 
import MySQLdb as mysql
 
conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb');
 
with conn:
 cursor = conn.cursor(mysql.cursors.DictCursor)
 cursor.execute("select * from writers where id = %s", "3")
 rows = cursor.fetchone()
 print "id is %d, name is %s" % (rows['id'], rows['name'])

我这里使用了一个%s的占位符来替换“3”,代表需要传入的是一个字符串类型。如果传入的不是string类型,则会运行报错。
事务
事务是指在一个或者多个数据库中对数据的原子操作。在一个事务中,所有的SQL语句的影响要不就全部提交到数据库,要不就全部都回滚。
对于支持事务机制的数据库,python接口在创建cursor的时候就开始了一个事务。可以通过cursor对象的commit()方法来提交所有的改动,也可以使用cursor对象的rollback方法来回滚所有的改动。
我这里写一个代码,对不存在的表进行插入操作,当抛出异常的时候,调用rollback进行回滚,实现代码如下:    
#!/usr/bin/python
 
# -*- coding: utf-8 -*-
 
import MySQLdb as mysql
 
 
try:
 conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb');
 cur = conn.cursor()
 cur.execute("insert into writers(name) values('wangzhengyi4')")
 cur.execute("insert into writers(name) values('bululu5')")
 cur.execute("insert into writerss(name) values('chenshan6')")
 
 conn.commit()
 
except mysql.Error, e:
 if conn:
  conn.rollback()
  print "Error happens, rollback is call"
 
finally:
 if conn:
  conn.close()

执行结果如下:    
Error happens, rollback is call
因为前两条数据是正确的插入操作,但是因为整体回滚,所以数据库里也没有wangzhengyi4和bululu5这两个数据的存在。


数据分析咨询请扫描二维码

客服在线
立即咨询