1.什麼是pymysql:PyMySQL 是在 Python3.x 版本中用於鏈接 MySQL 服務器的一個庫,Python2中則使用mysqldb。mysql
2.pymysql模塊是第三方的須要本身安裝:sql
# 1.安裝:pip3 insatll pymysql
3.基本語法使用數據庫
# 導入pymysql模塊 import pymysql # 鏈接到數據庫 conn = pymysql.connect( host = '127.0.0.1', # 數據庫ip地址 port = 3306, # 數據庫端口號 user = 'root', # 用戶名 password = '123', # 密碼 database = 'day38', # 數據庫 charset = 'utf8', # 編碼千萬不要加- 若是寫成了utf-8會直接報錯 autocommit = True # 這個參數配置完成後 增刪改操做都不須要在手動加conn.commit()了 ) # 產生遊標對象 cursor = conn.cursor(pymysql.cursors.DictCursor) # 產生一個遊標對象 每行數據 以字典的形式或列表套元組展示 鍵是表的字段名 值是表的字段值,不設置查詢結果解釋元組或元組套元組 # sql語句拼接 sql = sql語句 # 例:# sql = 'insert into user(name,password) values("jerry","666")' # 執行sql語句,sql注入和sql語句拼接後續再講 res = cursor.execute(sql) # # cursor.excutemany(sql,[(),(),()] # 一次插入多行記錄 # 獲取結果 # res = cursor.fetchone() # 獲取一條數據 # res = cursor.fetchmany(10) # 獲取10條數據,參數可修改 res = cursor.fetchall() # 獲取全部結果 遊標設置的話是列表裏面套字典 # 關閉 cursor.close() # 關閉遊標 conn.close() # 關閉鏈接 # 補充: cursor.scroll(2,'absolute') # 控制光標移動 absolute相對於其實位置 日後移動幾位,參數可修改 cursor.scroll(1,'relative') # relative相對於當前位置 日後移動幾位,參數可修改
4.sql注入服務器
1.什麼是sql注入:太過於相信用戶輸入的信息,用戶利用註釋等具備特殊意義的符號 來完成有漏洞的sql語句。ide
2.解決辦法:後續寫sql語句 不要手動拼接關鍵性的數據,而是讓excute幫你去作拼接fetch
3.案例:編碼
conn = pymysql.connect( host = '127.0.0.1', port = 3306, user = 'root', password = '123', database = 'day38', charset = 'utf8', # 編碼千萬不要加- 若是寫成了utf-8會直接報錯 autocommit = True # 這個參數配置完成後 增刪改操做都不須要在手動加conn.commit()了 ) cursor = conn.cursor(pymysql.cursors.DictCursor) # 產生一個遊標對象 以字典的形式返回查詢出來的數據 鍵是表的字段 值是表的字段對應的信息 username = input('username>>>:') password = input('password>>>:') # 注入問題 ''' sql = "select * from user where name =%s and password = %s" % (username,password) cursor.execute(sql) ''' # 解決方法 sql = "select * from user where name =%s and password = %s" res = cursor.execute(sql,(username,password)) # 可以幫你自動過濾特殊符號 避免sql注入的問題,execute 可以自動識別sql語句中的%s 幫你作替換,res是結果的數量整型 if res: print(cursor.fetchall()) else: print('用戶名或密碼錯誤')
# 增 sql = "insert into user(username,password) values(%s,%s)" rows = cursor.excute(sql,('jason','123')) # 修改 sql = "update user set username='jasonDSB' where id=1" rows = cursor.excute(sql) """ 增和改單單執行excute並不會真正影響到數據,須要再執行conn.commit()才能夠完成真正的增改 """ # 一次插入多行記錄 res = cursor,excutemany(sql,[(),(),()]