參數(shù)化
sql語句的參數(shù)化,可以有效防止sql注入
注意:此處不同于python的字符串格式化,全部使用%s占位
from pymysql import *
def main():
find_name = input("請輸入物品名稱:")
# 創(chuàng)建Connection連接
conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
# 獲得Cursor對象
cs1 = conn.cursor()
# # 非安全的方式
# # 輸入 " or 1=1 or " (雙引號也要輸入)
# sql = 'select * from goods where name="%s"' % find_name
# print("""sql===>%s<====""" % sql)
# # 執(zhí)行select語句,并返回受影響的行數(shù):查詢所有數(shù)據(jù)
# count = cs1.execute(sql)
# 安全的方式
# 構(gòu)造參數(shù)列表
params = [find_name]
# 執(zhí)行select語句,并返回受影響的行數(shù):查詢所有數(shù)據(jù)
count = cs1.execute('select * from goods where name=%s', params)
# 注意:
# 如果要是有多個(gè)參數(shù),需要進(jìn)行參數(shù)化
# 那么params = [數(shù)值1, 數(shù)值2....],此時(shí)sql語句中有多個(gè)%s即可
# 打印受影響的行數(shù)
print(count)
# 獲取查詢的結(jié)果
# result = cs1.fetchone()
result = cs1.fetchall()
# 打印查詢的結(jié)果
print(result)
# 關(guān)閉Cursor對象
cs1.close()
# 關(guān)閉Connection對象
conn.close()
if __name__ == '__main__':
main()