import pymysql
# 鏈接
conn = pymysql.connect(
user='root',
password='',
host='127.0.0.1',
port=3306,
charset='utf8',
database='day36'
)
# 遊標
# cursor = conn.cursor()
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 產生一個右遊標對象
# cursor=pymysql.cursors.DictCursor 將查詢出的結果製做成字典形式返回
sql = 'select * from user_info'
res = cursor.execute(sql) # 執行sql語句,返回sql查詢成功的記錄數目
# print(res)
# 查
# ret = cursor.fetchone() # 只獲取查詢結果中的一條數據
# ret = cursor.fetchall() # 獲取查詢結果的全部數據
# ret = cursor.fetchmany(2) # 指定獲取幾條數據,若是數字超過總數也不會報錯
# print(ret)
print(cursor.fetchone())
print(cursor.fetchone())
# 相對移動
# cursor.scroll(1, 'relative') # 基於指針所在的位置 日後偏移
# 絕對移動
cursor.scroll(3, 'absolute') # 基於起始位置 日後偏移
print(cursor.fetchall())
sql注入問題
'''
利用特殊符號和註釋語法,巧妙繞過真正的sql校驗
關鍵性的數據,不要本身手動去拼接,而是交由execute作拼接
'''
# sql注入之:用戶存在,繞過密碼
若輸入lzn' -- 任意字符 會顯示用戶信息
# sql注入之:用戶不存在,繞過用戶與密碼
若輸入xxx' or 1=1 -- 任意字符 會顯示全部信息 or後面的1=1條件永遠成立
import pymysql
conn = pymysql.connect(
user='root',
password='',
db='day36',
host='127.0.0.1',
port=3306,
charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 獲取用戶輸入的用戶名和密碼,而後去數據庫中校驗
username = input('username>>>:').strip()
password = input('password>>>:').strip()
# sql = "select * from user_info where name='%s' and password = '%s'"%(username, password)
# cursor.execute(sql)
sql = "select * from user_info where name=%s and password=%s"
cursor.execute(sql, [username, password])
res = cursor.fetchall()
if res:
print(res)
else:
print('username or password error!')
#解決方法
# sql = "select * from user_info where name='%s' and password='%s'"%(username,password)
# res = cursor.execute(sql)
#改寫爲(execute幫咱們作字符憑藉,咱們無需切必定不能再爲%s加引號,pymysql會自動加上)
# sql = "select * from user_info where name=%s and password=%s"
# res = cursor.excute(sql,[username, password])
數據的增刪改
import pymysql
conn = pymysql.connect(
user='root',
password='',
db='day36',
host='127.0.0.1',
port=3306,
charset='utf8',
autocommit = True # 自動提交確認
)
cursor = conn.cursor(cursor=pymysql.cursor.DictCursor)
# 增
sql = "insert into user_info(name, password) values('lll','111')"
# 改
sql = "update user_info set name='zzz' where id = 5"
# 刪除
sql = "delete from user_info where id = 1"
res = cursor.execute(sql)
# conn.commit() # 確認當前操做,真正同步到數據庫 已設置autocommit
print(res)
'''
針對增、刪、改操做,執行重要程度偏高,必需要有一步確認操做(commit)
'''