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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/17 11:28 # @Author : Ropon # @File : 55_01_pymysql.py
import pymysql
# user = input('请输入用户名:') # pwd = input('请输入密码:')
# 创建连接 conn = pymysql.connect( host='x.x.x.x', port=3306, user='xxx', password='xxx', db = 'testdb1', charset='utf8')
# 创建游标 # cursor = conn.cursor() # 默认情况下,获取返回的值是元组,只能看到每行的数据,但不知每一列的含义 # 可以使用以下方式返回字典,每一行的数据会生成一个字典 # 在实例化的时候,将属性cursor设置为pymysql.cursors.DictCursor cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 编写sql语句 # sql = "select * from userinfo where user='{0}' and passwd='{1}'".format(user, pwd) # sql = "select * from userinfo where user=%s and passwd=%s" # print(sql)
# 执行sql语句 # cursor.execute(sql) # result = cursor.execute(sql) # print(result)
# result = cursor.execute(sql, [user, pwd])
# if result: # print('登录成功') # else: # print('登录失败')
# sql注入 # sql语句中 -- 表示注释的意思 # 1、用户名存在,绕过密码 # ropon' -- test # 2、用户名不存在,绕过密码 # xxx' or 2=2 -- renyi
# 解决方案 # 原来我们采用字符串拼接方式执行sql语句 # sql = "select * from userinfo where user='{0}' and passwd='{1}'".format(user, pwd) # 现在改写为execute帮我们做字符串拼接,而且%s不能在加引号 # sql = "select * from userinfo where user=%s and passwd=%s" # result = cursor.execute(sql, [user, pwd])
# 增、删、改 conn.commit()
# 增 # sql = "insert into userinfo(user,passwd) values(%s, %s)" # insert_result = cursor.execute(sql,(user, pwd)) # 同时插入多条数据 # insert_result = cursor.executemany(sql, [('zhangsan', '123'), ('lisi', '234')]) # print(insert_result)
# 删 # sql ="delete from userinfo where user=%s" # user1 = 'lisi' # delete_result = cursor.execute(sql,user1) # print(delete_result)
# 改 # sql = "update userinfo set passwd = %s where user = %s" # newpasswd = '12345678' # user2 = 'ropon' # update_result = cursor.execute(sql, (newpasswd, user2)) # print(update_result)
# 查 sql = "select * from userinfo" select_result = cursor.execute(sql) # print(select_result)
# 获取下一行数据,第一次为首行 # fetchone() # cursor.scroll(2,mode='absolute') # d1 = cursor.fetchone() # print(d1) # # d1 = cursor.fetchone() # print(d1) # cursor.scroll(1, mode='relative')
# d1 = cursor.fetchone() # print(d1)
# fetchone 在获取行数据时,可以这么理解,开始有一个行指针指着第一行的上方 # 获取一行,它就向下移动一行,所以当指针到最后一行,就不能在获取行的内容 # 可以借助scroll方法移动行指针 # 相对当前位置移动,第一值移动的行数,正数向下移动,负数向上移动 # cursor.scroll(1, mode='relative')
# 绝对位置移动(基于首行移动),第一值移动的行数,正数向下移动,负数向上移动 # cursor.scroll(2,mode='absolute')
# 获取所有行数据 # fetchall # d2 = cursor.fetchall() # print(d2)
# 获取多少行数据 # fetchmany(2) # d3 = cursor.fetchmany(2) # print(d3)
# 提交保存 conn.commit()
# 关闭游标和连接 cursor.close() conn.close()
|