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

3.2.1 数据库---pymysql模块

时间:2018-06-20 21:16:24      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:style   oca   success   round   project   inf   ret   class   pychar   

# pip3 install pymysql

pycharm project Interpreter:  添加包 PyMySQL

 技术分享图片

 

技术分享图片
import sys
import pymysql

print(sys.path)


def login_db(user, pwd):


    conn = pymysql.connect(
        host=localhost,
        port=3306,
        user=root,
        passwd=!QAZxsw2,
        db=db1,
        charset=utf8
    )

    cur = conn.cursor()

    sql = "select username,pwd from user where username=‘%s‘ and pwd = ‘%s‘" % (user, pwd)
    rows = cur.execute(sql)

    cur.close()

    conn.close()

    if rows:
        print(success)
    else:
        print(failed)


if __name__ == __main__:
    user = input(user>>).strip()
    passwd = input(password>>).strip()

    login_db(user, passwd)
View Code

 注意:这种方法有sql注入的风险。

技术分享图片
运行结果:

user>>zdaf" or 1=1 -- adfa 
password>>asf
select username,pwd from user where username="zdaf" or 1=1 -- adfa" and pwd = "asf" 
success
View Code

 

防范sql注入的方式:

技术分享图片
import sys
import pymysql

print(sys.path)


def login_db(user, pwd):


    conn = pymysql.connect(
        host=localhost,
        port=3306,
        user=root,
        passwd=!QAZxsw2,
        db=db1,
        charset=utf8
    )

    cur = conn.cursor()

    # sql = ‘select username,pwd from user where username="%s" and pwd = "%s" ‘ % (user, pwd)
    # rows = cur.execute(sql)

    sql = select username,pwd from user where username=%s and pwd = %s
    rows = cur.execute(sql, (user, pwd))
    print(sql)

    cur.close()
    conn.close()

    if rows:
        print(success)
    else:
        print(failed)


if __name__ == __main__:
    user = input(user>>).strip()
    passwd = input(password>>).strip()

    login_db(user, passwd)
View Code
运行结果:
user>>lbx
password>>lbx
select username,pwd from user where username=%s and pwd = %s
success

user>>zdaf" or 1=1 -- adfa 
password>>
select username,pwd from user where username=%s and pwd = %s
failed

 

3.2.1 数据库---pymysql模块

标签:style   oca   success   round   project   inf   ret   class   pychar   

原文地址:https://www.cnblogs.com/beallaliu/p/9205001.html

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