Python使用pymysql模块操作mysql增删改查实例分析

yipeiwu_com6年前Python基础

本文实例讲述了Python使用pymysql模块操作mysql增删改查。分享给大家供大家参考,具体如下:

# -*- coding:utf-8 -*-
import pymysql
user = input('请输入用户名:')
pwd = input('请输入密码:')
# 1.连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123', db='t1', charset='utf8')
print(conn)
# 2.创建游标
cursor = conn.cursor()
#注意%s需要加引号
sql = "select * from t1.userinfo where username='%s' and pwd='%s'" %(user, pwd)
print(sql)
# 3.执行sql语句
cursor.execute(sql)
result=cursor.execute(sql) #执行sql语句,返回sql查询成功的记录数目
print(result)
# 关闭连接,游标和连接都要关闭
cursor.close()
conn.close()
if result:
 print('登陆成功')
else:
 print('登录失败')

下面是执行过程

请输入用户名:lisi
请输入密码:123
<pymysql.connections.Connection object at 0x000001BEFABFE240>
select * from t1.userinfo where username='lisi' and pwd='123'

登陆成功

二、execute()之sql注入

方式

#1、sql注入之:用户存在,绕过密码
lisi' -- 任意字符
#2、sql注入之:用户不存在,绕过用户与密码
xxx' or 1=1 -- 任意字符

请输入用户名:sdj;fja;' or 1=1 -- ;j;j;jj;jjkdsjfjsd
请输入密码:123
<pymysql.connections.Connection object at 0x000001EF2BE3E240>
select * from t1.userinfo where username='sdj;fja;' or 1=1 -- ;j;j;jj;jjkdsjfjsd' and pwd='123'

登陆成功

解决:

1采用列表的方式

# 原来是我们对sql进行字符串拼接
# sql="select * from userinfo where name='%s' and password='%s'" %(username,pwd)
# print(sql)
# result=cursor.execute(sql)
#改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)
sql="select * from userinfo where name=%s and pwd=%s" #!!!注意%s需要去掉引号,因为pymysql会自动为我们加上
result=cursor.execute(sql,[user,pwd]) #pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来。

2采用字典的方法

# -*- coding:utf-8 -*-
import pymysql
user = input('请输入用户名').strip()
pwd = input('请输入密码').strip()
# 连接服务端
conn = pymysql.connect(
 host='127.0.0.1',
 user='root',
 password="123",
 database='t1',
 port=3306,
 charset='utf8'
)
# -- ddadad
# 创建游标对象
cur = conn.cursor()
sql = "select * from userinfo where username = %(name)s and pwd = %(password)s"
print(sql)
# resultNum = cur.execute(sql,[user,pwd])
resultNum = cur.execute(sql,{"name":user,"password":pwd})
print(resultNum)
cur.close()
conn.close()
if resultNum:
 print('登陆成功')
else:
 print('登陆失败')

三、增、删、改:conn.commit()

commit()方法:在数据库里增、删、改的时候,必须要进行提交,否则插入的数据不生效。

基本框架

import pymysql
username = input('请输入用户名:')
pwd = input('请输入密码:')
# 1.连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='123', db='db8', charset='utf8')
# 2.创建游标
cursor = conn.cursor()
--------增删改操作----------------
#一定记得commit
conn.commit()
# 4.关闭游标
cursor.close()
# 5.关闭连接
conn.close()

增--》一组数据

sql='insert into userinfo(username,pwd) values(%s,%s)'
effect_row=cursor.execute(sql,(username,pwd)) # effect_row=1

增---》多组数据

sql='insert into userinfo(username,pwd) values(%s,%s)'
effect_row=cursor.executemany(sql,[('赵八','112'),('刘九','114'),('封十','911')]) #effect_row=3

sql='delete from userinfo where pwd like "%2"'
effect_row=cursor.execute(sql)

sql='update userinfo set username = %s where pwd="114"'
effect_row=cursor.execute(sql,'niu') #effect_row=2

 **上面的变量 effect_row=cursor.execute(...) ,返回的是成功改变的条目数字

四、查:fetchone、fetchmany、fetchall

表的内容

mysql> select * from userinfo;
+----+----------+-----+
| id | username | pwd |
+----+----------+-----+
| 1 | mjj  | 123 |
| 3 | 张三  | 110 |
| 4 | 李四  | 119 |
+----+----------+-----+
3 rows in set (0.00 sec)

固定格式

import pymysql
# 1.连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8')
# 2.创建游标
cursor = conn.cursor()
sql = 'select * from userinfo'
cursor.execute(sql)
------------执行的查询--------------
# 4.关闭游标
cursor.close()
# 5.关闭连接
conn.close()

fetchone查看一条符合条件的数据,可以连续使用,查询的是上一个fetchone的后面一条

# 查询第一行的数据
row = cursor.fetchone()
print(row) # (1, 'mjj', '123')
# 查询第二行数据
row = cursor.fetchone()
print(row) # (3, '张三', '110')

fetchall():查询所有符合条件的数据

# 获取所有的数据
rows = cursor.fetchall()
print(rows)
#运行结果
((1, 'mjj', '123'), (3, '张三', '110'), (4, '李四', '119')) 取到的返回值是元组

fetchmany:获取指定的条数数据

row=cursor.fetchmany(3)
print(row)

cursor.scroll(num,mode='relative|absolute')  当mode=absolute时,num不能小于0

cursor.scroll(1,mode='relative') # 相对当前位置移动
cursor.scroll(2,mode='absolute') # 相对绝对位置移动

# 查询第一行的数据
row = cursor.fetchone()
print(row) # (1, 'mjj', '123')
# 查询第二行数据
row = cursor.fetchone() # (3, '张三', '110')
print(row)
cursor.scroll(-1,mode='relative') #设置之后,光标相对于当前位置往前移动了一行,所以打印的结果为第二行的数据
row = cursor.fetchone()
print(row)
cursor.scroll(0,mode='absolute') #设置之后,光标相对于首行没有任何变化,所以打印的结果为第一行数据
row = cursor.fetchone()
print(row)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python常见数据库操作技巧汇总》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

今天在网上copy的一段代码,代码很简单,每行看起来该缩进的都缩进了,运行的时候出现了如下错误:  【解决过程】  1.对于此错误,最常见的原因是,的确没有缩进。...

python程序中的线程操作 concurrent模块使用详解

一、concurrent模块的介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 ProcessPo...

Python+PyQT5的子线程更新UI界面的实例

子线程里是不能更新UI界面的,在移动端方面。Android的UI访问是没有加锁的,多个线程可以同时访问更新操作同一个UI控件。也就是说访问UI的时候,android系统当中的控件都不是线...

python微信公众号之关键词自动回复

最近忙国赛的一个项目,我得做一个微信公众号。功能就是调数据并回复给用户,需要用户发送给公众号一个关键词,通过关键词自动回复消息。 这时就是查询微信公众平台文档了,地址如下: 文档 按照它...

Python一句代码实现找出所有水仙花数的方法

水仙花数是指一个 3位正整数,它的每个位上的数字的 3 次幂之和等于它本身。(例如:1^3 + 5^3+ 3^3 = 153) 下面用一句代码实现找出所有的水仙花数: 方法一: &g...