-- 受權加建立mysql帳號一步到位,%表明遠程 grant all on *.* to 'gudon'@'%' identified by '123'; mysql> flush privileges; -- 使操做結果當即生效 -- 建表 mysql> select * from userinfo; +----+--------+-------+ | id | user | pwd | +----+--------+-------+ | 1 | gudon | 123 | | 2 | Astro | 1234 | | 3 | Nurato | 12345 | +----+--------+-------+
# pip3 install pymysql import pymysql user = input('user>>').strip() pwd = input('pwd>>').strip() # 建鏈接 conn = pymysql.connect( host='127.0.0.1', port=3306, user='gudon', password='123', db='db9', charset='utf8' ) # 拿到遊標 cursor = conn.cursor() # 執行sql sql = 'select * from userinfo where user = "%s" and pwd = "%s"' %(user, pwd) rows = cursor.execute(sql) cursor.close() conn.close() # 進行判斷 if rows: print('登陸成功') else: print('登陸失敗') -------------------結果---------------------- user>>gudon pwd>>123 登陸成功
sql注入:python
user>>gudon "-- xxxx pwd>> 登陸成功 -- 此時sql 爲 select * from userinfo where user = "gudon "-- xxxx" and pwd = "" 後面的條件被註釋掉了 user>>xxx" or 1=1 -- xxx pwd>> 登陸成功 實際執行的sql爲 select * from userinfo where user = "xxx" or 1=1 -- xxx" and pwd = ""
sql注入解決辦法:mysql
# 執行sql sql = 'select * from userinfo where user=%s and pwd=%s' rows = cursor.execute(sql, (user, pwd))
import pymysql # 建鏈接 conn = pymysql.connect( host='127.0.0.1', port=3306, user='gudon', password='123', db='db9', charset='utf8' ) # 拿遊標 cursor = conn.cursor() # 執行sql # 增、刪、改 sql = 'insert into userinfo(user,pwd) values (%s,%s)' # 插入單條數據 # rows = cursor.execute(sql,('jack','123')) # print(rows) # 插入多條數據 rows = cursor.executemany(sql,[('gd01','123'),('gd02','123'),('zs','123')]) print(rows) conn.commit() # commit 後纔會真正更改數據庫中的數據 # 關閉 cursor.close() conn.close()
import pymysql # 建鏈接 conn = pymysql.connect( host='127.0.0.1', port=3306, user='gudon', password='123', db='db9', charset='utf8' ) # 拿遊標 # cursor = conn.cursor() cursor = conn.cursor(pymysql.cursors.DictCursor) # 使查詢結果爲字典格式 # 執行sql # 查 sql = 'select * from userinfo' # 插入單條數據 rows = cursor.execute(sql) # 返回查詢條數 # print(cursor.fetchone()) # (1, 'gudon', '123') # print(cursor.fetchone()) # (2, 'Astro', '1234') # 取到最後一個沒有數據了,則返回None print(cursor.fetchmany(2)) # 指定取出條數 # [{'id': 1, 'user': 'gudon', 'pwd': '123'}, {'id': 2, 'user': 'Astro', 'pwd': '1234'}] # print(cursor.fetchall()) # 取出全部 # cursor.scroll(3,mode='absolute') # 相對絕對位置移動,從0開始數3個,下次取第4條 # cursor.scroll(3,mode='relative') # 相對當前位置移動 ,相對於遊標目前的位置,日後數3個 # 關閉 cursor.close() conn.close()