pychar查询数据库

1.pycharm查询数据库

查询数据库

# 模块:pymysql  需要下载
import pymysql   # 导入模块
conn = pymysql.connect(
    host = '127.0.0.1',   # IP地址
    port = 3306, # 端口号
    user = 'root',    # 用户名
    password = '123',    # 密码
    database = 'day38', # 想要打开的数据库
    charset = 'utf8'  # 编码千万不要加- 如果写成了utf-8会直接报错
)
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 产生一个游标对象  以字典的形式返回查询出来的数据, 键是表的字段,值是表的字段对应的信息

sql = 'select * from teacher'
res = cursor.execute(sql)  # 执行传入的sql语句print(res)  # res接收执行语句返回的数据条数

print(cursor.fetchone())  # 只获取一条数据,读表中第一行数据
cursor.scroll(2,'absolute')  # 控制光标移动   absolute相对于起始位置,往后移动几位,也就是前几条不读
# cursor.scroll(1,'relative')  # relative相对于当前位置,往后移动几位,也就是跳过几条不读
print(cursor.fetchall())  # 获取所有的数据 ,返回的结果是一个列表

2.sql注入问题

1.sql注入

  就是利用注释等具有特殊意义的符号,来完成破解mysql验证。

一条sql语句中如果遇到select * from t1 where id > 3 -- andname='egon';那么--之后的条件被注释掉了

#1、sql注入之:用户存在,绕过密码
egon' -- 任意字符

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

 2.解决注入问题

# 原来是我们对sql进行字符串拼接
# sql="select * from userinfo where name='%s' and password='%s'" %(user,pwd)
# print(sql)
# res=cursor.execute(sql)

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

3.完整代码的演示

import pymysql
conn = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    password = '123',
    database = 'day38',
    charset = 'utf8',  # 编码千万不要加- 如果写成了utf-8会直接报错
    autocommit = True  # 这个参数配置完成后  增删改操作都不需要在手动加conn.commit了
)
cursor = conn.cursor(pymysql.cursors.DictCursor) 

username = input('username>>>:')
password = input('password>>>:')
sql = "select * from user where name =%s and password = %s"
print(sql)
res = cursor.execute(sql,(username,password))  # 能够帮你自动过滤特殊符号 避免sql注入的问题
# execute 能够自动识别sql语句中的%s 帮你做替换
if res:
    print(cursor.fetchall())
else:
    print('用户名或密码错误')
"""
后续写sql语句  不要手动拼接关键性的数据
而是让excute帮你去做拼接(将spl末尾的username,password放到cursor.execute()里面)
"""

 3.mysql的增删改

import pymysql
conn = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    password = '123',
    database = 'day38',
    charset = 'utf8',  # 编码千万不要加- 如果写成了utf-8会直接报错
    autocommit = True  # 这个参数配置完成后  增删改操作都不需要在手动加conn.commit了
)
cursor = conn.cursor(pymysql.cursors.DictCursor)

# sql = 'insert into user(name,password) values("jerry","666")'
# sql = 'update user set name = "jasonhs" where id = 1'
sql = 'delete from user where id = 6'
cursor.execute(sql)
# conn.commit() #上面配置后这里就不需要了

"""
增删改操作 都必须加一句
conn.commit()提交操作
"""
原文地址:https://www.cnblogs.com/blue-tea/p/11396982.html