python之pymysql模块
一、pymysql的安装
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。使用pip工具可以直接进行安装:
1pip install pymysql
二、操作数据库
1、执行SQL语句
1#!/usr/bin/env python
2# -*- coding:utf-8 -*-
3import pymysql
4# 创建连接
5conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
6# 创建游标
7cursor = conn.cursor()
8# 执行SQL,并返回收影响行数
9effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
10# 执行SQL,并返回受影响行数
11#effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))
12# 执行SQL,并返回受影响行数
13#effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
14# 提交,不然无法保存新建或者修改的数据
15conn.commit()
16# 关闭游标
17cursor.close()
18# 关闭连接
19conn.close()
2、获取新创建数据自增ID
1#!/usr/bin/env python
2# -*- coding:utf-8 -*-
3import pymysql
4conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
5cursor = conn.cursor()
6cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
7conn.commit()
8cursor.close()
9conn.close()
10# 获取最新自增ID
11new_id = cursor.lastrowid
3、获取查询数据
1#!/usr/bin/env python
2# -*- coding:utf-8 -*-
3import pymysql
4conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
5cursor = conn.cursor()
6cursor.execute("select * from hosts")
7# 获取第一行数据
8row_1 = cursor.fetchone()
9# 获取前n行数据
10# row_2 = cursor.fetchmany(3)
11# 获取所有数据
12# row_3 = cursor.fetchall()
13conn.commit()
14cursor.close()
15conn.close()
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
cursor.scroll(1,mode=’relative’) # 相对当前位置移动
cursor.scroll(2,mode=’absolute’) # 相对绝对位置移动
4、fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
1#!/usr/bin/env python
2# -*- coding:utf-8 -*-
3import pymysql
4conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
5# 游标设置为字典类型
6cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
7r = cursor.execute("call p1()")
8result = cursor.fetchone()
9conn.commit()
10cursor.close()
11conn.close()
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/python-pymsql/6066.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.