Python 数据库,操作mysql,防sql注入,参数化

demo.py(防sql注入):

from pymysql import *

def main():

    find_name = input("请输入物品名称:")

    # 创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()

    # 非安全的方式。  不要自己手动拼装sql语句。
    # sql = 'select * from goods where name="%s"' % find_name

    # 安全的方式
    # 构造参数列表
    params = [find_name]
    count = cs1.execute('select * from goods where name=%s', params)  # 通过params列表,自动填充%s  
    # 注意:
    # 如果要是有多个参数需要进行参数化
    # 那么params = [数值1, 数值2....],此时sql语句中有多个%s即可 
    
    result = cs1.fetchall()
    print(result)
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/84776791