摘要:本文主要向大家介绍了Python语言操作MySQL(一) PyMysql篇,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
本文主要向大家介绍了Python语言操作MySQL(一) PyMysql篇,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同,但是mysqldb不支持Python3
下载安装
pip3 install pymysql使用操作
1. 执行sql
#!/usr/bin/env python# -*- coding:utf-8 -*-import pymysql# 创建连接conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='test',charset='utf8')# 创建游标cursor = conn.cursor()# 执行SQL,并返回收影响行数effect_row = cursor.execute("update hosts set host = '1.1.1.2'")# 执行带条件SQL,并返回受影响行数#effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))# 执行SQL,并返回受影响行数#effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])# 提交,不然无法保存新建或者修改的数据conn.commit() # 获取最新自增IDnew_id = cursor.lastrowid# 关闭游标cursor.close()# 关闭连接conn.close()2.获取查询数据
#!/usr/bin/env python# -*- coding:utf-8 -*-import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')cursor = conn.cursor()cursor.execute("select * from hosts")# 获取第一行数据row_1 = cursor.fetchone()print(row_1)# 获取前n行数据# row_2 = cursor.fetchmany(3)# 获取所有数据row_3 = cursor.fetchall()cursor.close()conn.close()3.fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,使用设置游标为字典类型:
#!/usr/bin/env python# -*- coding:utf-8 -*-import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')# 游标设置为字典类型cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)r = cursor.execute("select * from hosts")result = cursor.fetchone()for k, v in result.items(): print(k,v)cursor.close()conn.close()
本文由职坐标整理并发布,希望对同学们学习Python有所帮助,更多内容请关注职坐标编程语言Python频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号