python操作MySQL


一、基本操作

  • 導入pymysql模塊
  • 建立數據庫連接對象conn
  • 通過conn創建操作sql的游標對象
  • 編寫sql交給cursor執行
  • 如果是查詢,通過cursor對象,獲取結果
  • 操作完畢,端口操作與連接
1)#導入pymysql模塊 import pymysql 2)#建立數據庫連接對象conn conn = pymysql.connect(user = 'root',password = '12345678',database = 'yjy') #此處還可以寫autocommit=True,待會可以自動提交事務 3)#通過conn創建操作sql的游標對象 cursor = conn.cursor(pymysql.cursors.DictCursor) # 注:游標不設置參數,查詢的結果就是數據元組,數據沒有標識性 # 設置pymysql.cursors.DictCursor,查詢的結果是字典,key是表的字段 4)#編寫sql交給cursor執行 # #先創建一個表 sql1 = 'create table tt(id int primary key auto_increment ,x int ,y int);' cursor.execute(sql1) mysql> desc tt; +-------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | x | int(11) | YES | | NULL | | | y | int(11) | YES | | NULL | | +-------+---------+------+-----+---------+----------------+ #插入數據 # sql2 = 'insert into tt values(%s, %s, %s)' sql2 = 'insert into tt(x,y) values(%s, %s)' cursor.execute(sql2,(1,10)) cursor.execute(sql2,(2,20)) cursor.execute(sql2,(3,30)) conn.commit() #在建立對象conn時不設置autocommit=True時,必須要提交事務,不然的話寫不到數據庫 mysql> select * from tt; +----+------+------+ | id | x | y | +----+------+------+ | 1 | 1 | 10 | | 2 | 2 | 20 | | 3 | 3 | 30 | +----+------+------+ '''還可以插入多條數據''' cursor.executemany(sql2,[(4,40),(5,50),(6,60)]) #這里是executemany,而且一定要記住中括號 conn.commit() +----+------+------+ | id | x | y | +----+------+------+ | 1 | 1 | 10 | | 2 | 2 | 20 | | 3 | 3 | 30 | | 4 | 4 | 40 | | 5 | 5 | 50 | | 6 | 6 | 60 | +----+------+------+ '''刪''' sql3= 'delete from tt where id = %s' cursor.executemany(sql3,(2,3,4,5)) conn.commit() +----+------+------+ | id | x | y | +----+------+------+ | 1 | 1 | 10 | | 6 | 6 | 60 | +----+------+------+ '''改''' sql4 = 'update tt set y=888 where id = 6' cursor.execute(sql4) conn.commit() +----+------+------+ | id | x | y | +----+------+------+ | 1 | 1 | 10 | | 6 | 6 | 888 | +----+------+------+ '''查''' sql5 = 'select * from tt' res = cursor.execute(sql5) print(res) #8 5)#如果是查詢,通過cursor對象,獲取結果 r1 = cursor.fetchone() #偏移一條數據取出 print(r1) #{'id': 1, 'x': 1, 'y': 10} r2 = cursor.fetchmany(3) #偏移3條數據取出 print(r2) #[{'id': 2, 'x': 2, 'y': 20}, {'id': 3, 'x': 3, 'y': 30}, {'id': 4, 'x': 4, 'y': 40}] r3 = cursor.fetchall() #把偏移后剩余的全部取出來 print(r3) #[{'id': 5, 'x': 5, 'y': 50}, {'id': 6, 'x': 6, 'y': 60}, {'id': 7, 'x': 7, 'y': 70}, {'id': 8, 'x': 8, 'y': 80}] 6)#操作完畢,端口操作與連接 cursor.close() #關閉游標對象 conn.close() #關閉數據庫連接對象

二、事務

import pymysql conn = pymysql.connect(user = 'root',password = '12345678',database = 'yjy') cursor = conn.cursor(pymysql.cursors.DictCursor) #對表的重復創建做一個異常處理,防止報錯 try: sql1 = 'create table ts(id int primary key auto_increment ,name char(8),money int)' cursor.execute(sql1) except Exception: print('表已經創建') pass #在空表中插入數據 row = cursor.execute('select * from ts') #檢查一下表里面是否有數據 if not row: #如果沒有數據,插入數據 sql = 'insert into ts(name,money) values(%s,%s)' res = cursor.executemany(sql, [('yjy', 10), ('wwb', 30)]) conn.commit() #在事務中出現的失敗,處理一下異常 try: sql1 = 'update ts set money=money-1 where name="yjy"' r1 = cursor.execute(sql1) sql2 = 'update ts set money=money+1 where name="wwb"' # 轉入的人不存在 r2 = cursor.execute(sql2) except: print('轉賬執行異常') conn.rollback() #回滾 else: print('轉賬沒有異常') if r1 == 1 and r2 == 1: print('轉賬成功') conn.commit() #提交事務 else: conn.rollback() #回滾 mysql> select * from ts; +----+------+-------+ | id | name | money | +----+------+-------+ | 1 | yjy | 10 | | 2 | wwb | 30 | +----+------+-------+ 2 rows in set (0.00 sec) mysql> select * from ts; +----+------+-------+ | id | name | money | +----+------+-------+ | 1 | yjy | 9 | | 2 | wwb | 31 | +----+------+-------+ 2 rows in set (0.00 sec)

三、sql注入

import pymysql from pymysql.cursors import DictCursor conn = pymysql.connect(user='root', passwd='12345678', db='yjy') cursor = conn.cursor(DictCursor) try: sql = 'create table user(id int primary key auto_increment, name char(4), password char(6))' row = cursor.execute(sql) print(row) except: print('表已創建') pass # 空表才插入 row = cursor.execute('select * from user') if not row: sql = 'insert into user(name,password) values(%s,%s)' row = cursor.executemany(sql, [('yjy', '123'), ( 'wwb', 'abc')]) conn.commit() # 用戶登錄 usr = input('usr: ') pwd = input('pwd: ') #數據庫驗證 sql = 'select * from user where name=%s and password=%s' row = cursor.execute(sql, (usr, pwd)) if row: print('登錄成功') else: print('登錄失敗') # 自己拼接參數一定有sql注入,將數據的占位填充交給pymysql,下面這個方式是不正確的,對數據庫中的數據不安全,用戶隨便用符號就可以登陸進去,所以,我們在上面的數據庫驗證得時候改了格式 """ sql = 'select * from user where name="%s" and password="%s"' % (usr, pwd) row = cursor.execute(sql) if row: print('登錄成功') else: print('登錄失敗') """ # 知道用戶名時 # 輸入用戶時: # yjy" # => select * from user where name="yjy" #" and password="%s" # 不自定義用戶名時 # " or 1=1 # => select * from user where name=" " or 1=1 #" and password="%s"(就不需要輸入密碼了) ——————————————————————————————————————————————————————————————————————————————————— usr: yjy pwd: 123 登錄成功

四、索引

  • 是添加給數據庫表的字 的
  • 給表創建鍵后該表不僅會形成表結構、表數據,還有鍵的B+結構圖(加速查找的一個圖)
  • 鍵的結構圖是需要維護的,在數據完成增、刪、改操作時,只要影響到有鍵的字段,結構圖都要維護一次
  • 創建鍵后一定會降低 增、刪、改 的效
  • 鍵可以極大的加快查詢速度(開發需求中,幾乎業務都和查有關系)
  • 建立鍵的方式:主鍵、外鍵、唯一鍵、index
#上面這個沒有什么好說的,意思就是,當我們數據達到幾十萬條,幾千萬條,用索引查找時間會更快,這就是給表創建鍵的好處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM