Python 操作 MySQL--(pymysql)

pymysql

pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。

1、下载安装

pip3 install pymysql

2、执行SQL

执行SQL语句的基本语法:

需要注意的是:创建连接后,都由游标来进行与数据库的操作,因而获取数据也需要游标。

#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'wyf'

import pymysql

#创建链接
conn = pymysql.connect(host='192.168.14.88',port=3306,user='root',passwd='123456',db='hive_test')
#创建游标

cursor = conn.cursor()
#print cursor

#执行语句,返回数据结果总数量
effect_new = cursor.execute('select * from A')
#print effect_new
#结果是 7
# 执行SQL,并返回受影响行数
effect_row = cursor.executemany('select * from A where aID=%s',[3,4,5])
print effect_row
#结果是3
# 提交,不然无法保存新建或者修改的数据
conn.commit()

# 关闭游标
cursor.close()
# 关闭连接
conn.close()

3.获取新建数据的自增ID

可以获取到最新自增的ID,也就是最后插入的一条数据ID

#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'wyf'

import pymysql

#创建链接
conn = pymysql.connect(host='192.168.14.88',port=3306,user='root',passwd='123456',db='hive_test')
#创建游标

cursor = conn.cursor()
#print cursor

# 执行SQL,并返回受影响行数
effect_row = cursor.executemany('insert into A(aNum) values(%s)',['ggg','hhhh','ffff'])

# 提交,不然无法保存新建或者修改的数据
conn.commit()
print cursor.fetchall()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

# 获取最新自增ID,注意是最新的id,多条也是一条
new_id = cursor.lastrowid
print new_id

4、获取查询数据

获取查询数据的三种方式:获取第一行数据,获取前n行数据,获取所有数据 (数据是以元祖的方式存放)

#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'wyf'

import pymysql

#创建链接
conn = pymysql.connect(host='192.168.14.88',port=3306,user='root',passwd='123456',db='hive_test')
#创建游标

cursor = conn.cursor()
#print cursor

#获取所有数据
cursor.execute('select * from A')

#获取第一条数据
row_1 = cursor.fetchone()
print 'row_1=',row_1
#获取前N条数据
row_n = cursor.fetchmany(3)
print 'row_n=',row_n
# 获取所有数据
row_all = cursor.fetchall()
print 'row_all=',row_all
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

结果:

注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:

  • cursor.scroll(1,mode='relative')  # 相对当前位置移动
  • cursor.scroll(2,mode='absolute') # 相对绝对位置移动

示例:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'wyf'

import pymysql

#创建链接
conn = pymysql.connect(host='192.168.14.88',port=3306,user='root',passwd='123456',db='hive_test')
#创建游标

cursor = conn.cursor()
#print cursor

#获取所有数据
cursor.execute('select * from A')
#所有查询数据都打印一编,方便对比
print '''row_all= ((1, 'a20050111'), (9, 'sdasdas'), (3, 'a20050113'), (4, 'a20050114'), (5, 'a20050115'), (6, 'a20160928'), (7, 'sdasdasdadasd'), (8, 'sdasdasdadasd'), (17, 'ffff'), (16, 'hhhh'), (15, 'ggg'))'''
cursor.scroll(1, mode='relative')  # 相对当前位置移动
row_all_1 = cursor.fetchone()
print 'row_all_1=',row_all_1
cursor.scroll(2, mode='absolute')  # 相对绝对位置移动
row_all_2 = cursor.fetchone()
print 'row_all_2=',row_all_2
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

结果:

总结:

1.当用fetchall的时候游标指针会移动到最后,请在使用scroll的时候注意。

2.结果分析,相对是当前指针的位置,绝对是指针整体位置。

3.(1, mode='relative') 当前指针下移一个的位置,及地第二个,(2, mode='absolute'),最初的指针下移两个,因为这个结果指针最初都是最开始。

5.fetch数据类型

默认拿到的数据是元祖类型,如果是字典的话会更方便操作,那方法来了:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'wyf'

import pymysql

#创建链接
conn = pymysql.connect(host='192.168.14.88',port=3306,user='root',passwd='123456',db='hive_test')
#创建游标

cursor = conn.cursor()
#print cursor

# 游标设置为字典类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
r = cursor.execute("select * from A")
result = cursor.fetchone()
print 'result=',result
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

6.利用with自动关闭

# 利用with定义函数

    @contextlib.contextmanager
    def mysql(self, host='192.168.14.88',port=3306,user='root',passwd='123456',db='hive_test', charset='utf8'):
        self.conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset)
        self.cuersor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

        try:
            yield self.cuersor
        finally:
            self.conn.commit()
            self.cuersor.close()
            self.conn.close()

# 执行
with mysql() as cuersor:
   print(cuersor)
   # 操作MySQL代码块
posted @ 2016-10-09 15:15  楚时邀月  阅读(369)  评论(0编辑  收藏  举报