Python进行MySQL数据库操作

最近开始玩Python,慢慢开始喜欢上它了,以前都是用shell来实现一些自动化或者监控的操作,现在用Python来实现,感觉更棒,Python是一门很强大的面向对象语言,所以作为一个运维DBA或者运维来说,都应该学会用Python来提高工作效率。下面简单的介绍一下Python DB API MySQLdb

 

 

使用Python DB API访问数据库的流程图:

技术分享

 

在Centos下安装MySQLdb模板(为了方便演显,我用yum安装,也是最快最省事的安装):

yum install MySQL-python -y

如果安装有ipython,可以看到它有非常多的对象,每个对象这里就介绍ipython的安装:

In [1]: import MySQLdb
In [2]: MySQLdb. MySQLdb.BINARY MySQLdb.NotSupportedError MySQLdb.escape_sequence MySQLdb.Binary MySQLdb.OperationalError MySQLdb.escape_string MySQLdb.Connect MySQLdb.ProgrammingError MySQLdb.get_client_info MySQLdb.Connection MySQLdb.ROWID MySQLdb.paramstyle MySQLdb.DATE MySQLdb.STRING MySQLdb.release MySQLdb.DATETIME MySQLdb.TIME MySQLdb.result MySQLdb.DBAPISet MySQLdb.TIMESTAMP MySQLdb.server_end MySQLdb.DataError MySQLdb.Time MySQLdb.server_init MySQLdb.DatabaseError MySQLdb.TimeFromTicks MySQLdb.string_literal MySQLdb.Date MySQLdb.Timestamp MySQLdb.test_DBAPISet_set_equality MySQLdb.DateFromTicks MySQLdb.TimestampFromTicks MySQLdb.test_DBAPISet_set_equality_membership MySQLdb.Error MySQLdb.Warning MySQLdb.test_DBAPISet_set_inequality MySQLdb.FIELD_TYPE MySQLdb.apilevel MySQLdb.test_DBAPISet_set_inequality_membership MySQLdb.IntegrityError MySQLdb.connect MySQLdb.thread_safe MySQLdb.InterfaceError MySQLdb.connection MySQLdb.threadsafety MySQLdb.InternalError MySQLdb.constants MySQLdb.times MySQLdb.MySQLError MySQLdb.debug MySQLdb.version_info MySQLdb.NULL MySQLdb.escape MySQLdb.NUMBER MySQLdb.escape_dict

 我们这里主要说创建数据库的连接对象connection,创建方法MySQLdb.connect(参数)

主要参数如下:

  参数名    类型      说明
  host     字符串    MySQL服务器地址
  port     数字      MySQL服务器端口号
  user     字符串    用户名
  passwd   字符串    密码
  db       字符串    数据库名称
  charset  字符串    连接编码

 connection对象支持的方法:

方法名        说明
cursor()    使用该连接创建并返回游标
commit()    提交当前事务
rollback()  回滚当前事务
close()     关闭连接

实例讲解:编辑connection.py


#!/usr/bin/env python

# coding:utf-8 # name: connection.py import MySQLdb # 创建连接 conn = MySQLdb.connect( host = ‘ 127.0.0.1 ‘ , port = 3306 , user = ‘ root ‘ , passwd = ‘ 123456 ‘ , db = ‘ python ‘ , charset = ‘ utf8 ‘ ) # 创建一个学游标对象 cursor = conn.cursor() print conn print cursor # 关闭游标 关闭连接 cursor.close() conn.close()

执行结果:

[root@Test-server script]#python connection.py 
<_mysql.connection open to ‘127.0.0.1‘ at 23c1fa0>
<MySQLdb.cursors.Cursor object at 0x7f545cbf97d0>
[root@Backup-server script]#vim connection.py

可以看到成功连接了MySQL.

 

下面介绍一下游标对象: 用于执行查询和获取结果 

cursor对象支持的方法:

参数名               说明
execute(op[,args])   执行一个数据查询命令
fetchone()           取的结果集的下一行
fetchmany(size)      获取结果集的下几行
fetchall()           获取结果集中剩下的所有行
rowcount             最近一次execute返回的行数或影响行数
close()              关闭游标对象

 

execute方法:执行SQL、将结果从数据为获取到客户端:
技术分享

fetch*()方法:移动rownumber,返回数据。

 

实例演示:(select查询数据)

技术分享

 

创建一张测试:

CREATE TABLE `user` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
mysql> select * from user;
+--------+----------+
| userid | username |
+--------+----------+
|      1 | user1    |
|      2 | user2    |
|      3 | user3    |
|      4 | user4    |
|      5 | user5    |
|      6 | user6    |
|      7 | user7    |
|      8 | user8    |
|      9 | user9    |
+--------+----------+
9 rows in set (0.00 sec)

编辑cursor.py文件:

#!/usr/bin/env python




# coding:utf-8 # name: cursor.py import MySQLdb conn = MySQLdb.connect( host = ‘ 127.0.0.1 ‘ , port = 3306 , user = ‘ root ‘ , passwd = ‘ 123456 ‘ , db = ‘ python ‘ , charset = ‘ utf8 ‘ ) cursor = conn.cursor() sql = “ select * from user ” cursor.execute(sql) # 打印所有行数据 print cursor.rowcount # 打印第一行数据 rs = cursor.fetchone() print “ 返回一条数据 ” ,rs # 打印从第二行起的三行数据 rs = cursor.fetchmany(3 ) print “ 返回从第二条起的三条数据 ” ,rs # 打印剩下的所有行数 rs = cursor.fetchall() print “ 返回剩下的行数据 ” ,rs cursor.close() conn.close()

运行程序:

[root@Test-server script]#python connection.py 
9
返回一条数据 (1L, u‘user1‘)
返回从第二条起的三条数据 ((2L, u‘user2‘), (3L, u‘user3‘), (4L, u‘user4‘))
返回剩下的行数据 ((5L, u‘user5‘), (6L, u‘user6‘), (7L, u‘user7‘), (8L, u‘user8‘), (9L, u‘user9‘))

我们看到,每次使用fetch方法,都是在上一次fetch方法执行的结果的尾部开始。

如果我们想把表里的数据格式化打印出来,因为从上面的结果我们可以看到返回的是元组的元组,我们通过for方法把它取出:

#!/usr/bin/env python




# coding:utf-8 # name: cursor.py import MySQLdb conn = MySQLdb.connect( host = ‘ 127.0.0.1 ‘ , port = 3306 , user = ‘ root ‘ , passwd = ‘ 123456 ‘ , db = ‘ python ‘ , charset = ‘ utf8 ‘ ) cursor = conn.cursor() sql = “ select * from user ” cursor.execute(sql)
#获取所有行的数据 rs = cursor.fetchall() for row in rs: print “ userid=%s, username=%s ” % row cursor.close() conn.close()

执行程序:

[root@Test-server script]#python cursor.py 
userid=1, username=user1
userid=2, username=user2
userid=3, username=user3
userid=4, username=user4
userid=5, username=user5
userid=6, username=user6
userid=7, username=user7
userid=8, username=user8
userid=9, username=user9

 

 

对MySQL的insert/delete/update的操作演示:

技术分享

 

编辑一个增删改的脚本iud.py

#!/usr/bin/env python




# coding:utf-8 # name: iud.py import MySQLdb conn = MySQLdb.connect( host = ‘ 127.0.0.1 ‘ , port = 3306 , user = ‘ root ‘ , passwd = ‘ 123456 ‘ , db = ‘ python ‘ , charset = ‘ utf8 ‘ ) cursor = conn.cursor() # 插入sql sql_insert = “ insert into user (userid,username) values (10,‘user10‘) ” # 更新sql sql_update = “ update user set username= ‘name91‘ where userid=9 ” # 删除sql sql_delete = “ delete from user where userid < 3 ” # 把一个事务放到一个try块里,如果出现异常就回滚 try : cursor.execute(sql_insert) print cursor.rowcount cursor.execute(sql_update) print cursor.rowcount cursor.execute(sql_delete) print cursor.rowcount # 提交事务 conn.commit() # 格式化增删改后的数据查出来 select_sql = “ select * from user ” cursor.execute(select_sql) rs = cursor.fetchall() for row in rs: print “ userid=%s, username=%s ” % row except Exception as e: conn.rollback() # 若有异常就回滚

执行程序,结果如下:

root@Test-server script]#python iud.py 
1
1
2
userid=3, username=user3
userid=4, username=user4
userid=5, username=user5
userid=6, username=user6
userid=7, username=user7
userid=8, username=user8
userid=9, username=name91
userid=10, username=user10

 

 

通过上面的简单例子说明了通过Python的MySQLdb模块去进行MySQL数据库操作,网上有很多例子,我是Python菜鸟,通过参加慕课网的一些简单直接的python课程学习,个人感觉还不错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值