Python中操作mysql的pymysql模块详解

本文详细介绍了Python中用于操作MySQL的pymysql模块,包括安装、执行SQL、获取查询数据、处理游标、数据类型转换、调用存储过程及防止SQL注入的方法。强调了使用参数化查询和存储过程来避免注入问题,并展示了如何使用with语句简化连接操作。
摘要由CSDN通过智能技术生成

前言

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

本文测试python版本:2.7.11。mysql版本:5.6.24

一、安装

1

pip3 install pymysql

二、使用操作

1、执行SQL

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

#!/usr/bin/env pytho

# -*- coding:utf-8 -*-

import pymysql

  

# 创建连接

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

# 创建游标

cursor = conn.cursor()

  

# 执行SQL,并返回收影响行数

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

  

# 执行SQL,并返回受影响行数

#effect_row = cursor.execute("update tb7 set pass = '123' where nid = %s", (11,))

  

# 执行SQL,并返回受影响行数,执行多次

#effect_row = cursor.executemany("insert into tb7(user,pass,licnese)values(%s,%s,%s)", [("u1","u1pass","11111"),("u2","u2pass","22222")])

  

  

# 提交,不然无法保存新建或者修改的数据

conn.commit()

  

# 关闭游标

cursor.close()

# 关闭连接

conn.close()

注意:存在中文的时候,连接需要添加charset='utf8',否则中文显示乱码。

2、获取查询数据

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#! /usr/bin/env python

# -*- coding:utf-8 -*-

# __author__ = "TKQ"

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')

cursor = conn.cursor()

cursor.execute("select * from tb7")

# 获取剩余结果的第一行数据

row_1 = cursor.fetchone()

print row_1

# 获取剩余结果前n行数据

# row_2 = cursor.fetchmany(3)

# 获取剩余结果所有数据

# row_3 = cursor.fetchall()

conn.commit()

cursor.close()

conn.close()

3、获取新创建数据自增ID

可以获取到最新自增的ID,也就是最后插入的一条数据ID

1

2

3

4

5

6

7

8

9

10

11

12

13

14

#! /usr/bin/env python

# -*- coding:utf-8 -*-

# __author__ = "TKQ"

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')

cursor = conn.cursor()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值