微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python pymysql模块安装并操作过程解析

这篇文章主要介绍了Python pyMysqL模块安装并操作过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

pymsql是Python中操作MysqL的模块,其使用方法MysqLdb几乎相同。但目前pyMysqL支持python3.x而后者不支持3.x版本。

本文环境 python3.6.1 MysqL 5.7.18

1、安装模块

pip3 install pyMysqL

2、python操作

1) 获取查询数据

#!/usr/bin/env python # -*- coding:utf-8 -*- import pyMysqL # 创建连接 conn = pyMysqL.connect(host='127.0.0.1', port=3306, user='root', passwd='redhat', db='homework',charset='utf8') # 创建游标 cursor = conn.cursor() # 执行sql cursor.execute("select * from student") #获取剩余结果的第一行数据 #row_1 = cursor.fetchone() #获取前n行数据 #row_2 = cursor.fetchmany(3) #获取所有查询数据 row_3 = cursor.fetchall() print(row_3) # 提交,不然无法保存新建或者修改的数据 conn.commit() # 关闭游标 cursor.close() # 关闭连接 conn.close()

2、获取新创建数据的自增id

最后插入的一条数据id

#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "Yu" import pyMysqL conn = pyMysqL.connect(host='127.0.0.1',port=3306, user='root', passwd='redhat', db='db3') cursor = conn.cursor() effect_row = cursor.executemany("insert into tb11(name,age) values(%s,%s)", [("yu","25"),("chao", "26")]) conn.commit() cursor.close() conn.close() # 获取自增id new_id = cursor.lastrowid print(new_id)

3、fetch数据类型

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

#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "Yu" import pyMysqL conn = pyMysqL.connect(host='127.0.0.1',port=3306, user='root', passwd='redhat', db='db3') #游标设置为字典类型 cursor = conn.cursor(cursor=pyMysqL.cursors.DictCursor) cursor.execute("select * from tb11") row_1 = cursor.fetchone() print(row_1) conn.commit() cursor.close() conn.close()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐