36-2 python操作mysql

本篇对于Python操作MySQL主要使用两种方式:

  • 原生模块 pymsql
  • ORM框架 SQLAchemy
pymysql

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

一、下载安装

因为pip3.exe文件是在C:\Program Files\Python36\Scripts目录下,所以需要先将此目录加入环境变量,这样cmd执行时才能直接找到。

pip3 install pymysql

安装完后可以在C:\Program Files\Python36\Lib\site-packages目录下看到有了pymysql文件夹。

二、使用

 1、增、删、改数据

import pymysql

# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='sc', charset='utf8')
# 创建游标
cursor = conn.cursor()

# 插入单行
effect_row = cursor.execute("insert into class(cid,caption)values(%s,%s)", ("7","三年七班"))
print(effect_row)   # 受影响的行数
# 插入多行
# l=[(5,"三年五班"),(6,"三年六班")]    # 可迭代对象即可,不是非得是list
# effect_row = cursor.executemany("insert into class(cid,caption)values(%s,%s)", l)

# 修改
# effect_row = cursor.execute("update class set caption='三年四班' where cid='4'")

# 删除
# effect_row = cursor.execute("delete from class  where cid=%s", "7")

# 增删改都需要commit,不然无法保存新建或者修改的数据.仅查询时不用写
conn.commit()

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

插入完数据后,可以获取最后一条记录的自增ID(即便cursor和conn都关闭也能获得到):

# 获取最新自增ID
new_id = cursor.lastrowid

注意:为防止sql注入,不允许通过字符串拼接的方式组成sql语句,而要使用参数传入的方式。

2、查询数据

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='sc', charset='utf8')
cursor = conn.cursor()

effect_row = cursor.execute("select * from student")

# fetchall                         # 所有的都拿出来
# ret = cursor.fetchall()

# fetchone
ret = cursor.fetchone()            # 内部维护着一个指针,一次拿一条
print(ret)
ret = cursor.fetchone()
print(ret)
ret = cursor.fetchone()
print(ret)

# fetchmany
# ret = cursor.fetchmany(3)        # 从指针位置起往下拿3条
# print(ret)

cursor.close()
conn.close()

关于fetch:

(1)指针位置的移动

在fetch数据时按照顺序进行(内部维护着一个指针),可以使用cursor.scroll(num,mode)来移动游标(指针)位置,如:

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

  (2)fetch数据类型

默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:

import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='sc', charset='utf8')

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)    # 游标设置为字典类型

effect_row = cursor.execute("select * from class")
conn.commit()
ret=cursor.fetchone()
print(ret)             # {'cid': 1, 'caption': '三年二班'}   可以通过键直接取值了
cursor.close()
conn.close()

  

  

 

  

 

  

参考:http://www.cnblogs.com/wupeiqi/articles/5713330.html

posted @ 2017-09-18 22:17  seaidler  阅读(171)  评论(0)    收藏  举报