python36 mysql_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

f26a7b58365ec800b85102a6e5cd9d4a.png

安装完后可以在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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值