码迷,mamicode.com
首页 > 数据库 > 详细

python 操作 MySQL 即相关问题

时间:2019-08-22 21:52:29      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:变量   赋值   列表   etc   div   自动   values   database   返回   

导入pymysql

import pymysql

# 创建connect()对象
conn = pymysql.connect(
    host = 127.0.0.1,
    port = 3306,
    user = root,
    password = root,
    database = db1,
    charset = utf8
)
# 产生一个游标对象 以字典的形式返回查询出来的数据,键是表的字段,值时字段对应的记录
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 编写sql语句,赋值给一个变量
sql = select * from teacher
# 执行传入的sql语句
res = cursor.execute(sql)
# print(res)  # res 是执行语句返回的数据条数
print(cursor.fetchone())  # fetchone只获取一条数据 {‘tid‘: 1, ‘tname‘: ‘张磊老师‘}
print(cursor.fetchone())  # 只获取一条数据 {‘tid‘: 2, ‘tname‘: ‘李平老师‘} 获取的是第二条数据,因为游标在移动

# 控制光标移动
cursor.scroll(1,absolute)  # absolute 绝对移动,相对起始位置,往后移动几位
cursor.scroll(1,relative)  # relative 相对移动,现对于当前光标所在位置,往后移动几位

print(cursor.fetchall())  # fetchall获取所有数据,返回的是一个列表
# [{‘tid‘: 1, ‘tname‘: ‘张磊老师‘}, {‘tid‘: 2, ‘tname‘: ‘李平老师‘},
# {‘tid‘: 3, ‘tname‘: ‘刘海燕老师‘}, {‘tid‘: 4, ‘tname‘: ‘朱云海老师‘},
# {‘tid‘: 5, ‘tname‘: ‘李杰老师‘}]

 

增删改查

import pymysql

conn = pymysql.connect(
    host = 127.0.0.1,
    port = 3306,
    user = root,
    password = root,
    database = db2,
    charset = utf8,
    autocommit = True  # 这个参数配置后,增删改操作都不会需要手动加conn.commit了

)
cursor = conn.cursor(pymysql.cursors.DictCursor)

‘‘‘
增删改操作对于数据库来说都是敏感操作
都必须加一句 conn.commit()
‘‘‘
# conn.commit()
# sql = ‘insert into user(id,name,password) values(3,"dazhuang","321")‘  # 增数据
# sql = ‘update user set name = "xiaozhuang" where id = 3‘  # 改数据
# sql = ‘delete from user where id = 3‘  # 删数据
# cursor.execute(sql)

username = input(>>>:)
pwd = input(>>>:)
sql = "select * from user where name = %s and password = %s"  # 查数据
print(sql)
# 根据sql语句匹配用户输入的名合密码是否存在
res = cursor.execute(sql,(username,pwd))  # 能帮你自动过滤特殊符号,不免sql注入问题
# execute 能自动识别sql语句中的%s 帮你做替换
print(res)  # 若存在 返回的是数据的条数1,不存在返回的是0条数据
# 判断 res 是否有值
if res:
    print(cursor.fetchall())
else:
    print(用户名或密码错误)

 

 sql注入问题

sql 注入问题:
    就是利用注释等具有特殊意义的符号来利用mysql的漏洞
    
解决办法:
    利用excute帮你去拼接数据
    
    将 sql = "select * from user where name = %s and password = %s" %(username,pwd)
    改为: sql = "select * from user where name = %s and password = %s" 
            res = cursor.execute(sql,(username,pwd))

 

python 操作 MySQL 即相关问题

标签:变量   赋值   列表   etc   div   自动   values   database   返回   

原文地址:https://www.cnblogs.com/waller/p/11396919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!