python學習4--python3連mysql增刪改查
阿新 • • 發佈:2020-08-17
前言
pymysql是在Python3.x版本中用於連線MySQL伺服器的一個庫,Python2中則使用mysqldb。
環境準備
python3.7
使用pip安裝PyMySQL
pip install pymysql
先使用第三方工具連線mysql資料庫,比如navicat連線mysql
連線名:隨便命名
主機名或ip地址:mysql服務的ip地址
埠:3306 (埠號,預設一般是3306)
使用者名稱:root (授權遠端登陸的使用者名稱)
密碼:123456 (授權遠端登陸的密碼)
查詢操作
如存在一個aiopms資料庫,裡面有一張pms_knowledges_sort,有sortid、name、desc、status四個欄位,使用sql查詢結果如下
接下來使用python轉換成對應的程式碼查詢
# coding:utf-8 import pymysql #開啟資料庫連線 c=pymysql.connect(host='47.98.66.11', port=3306, user='root', password='P@ssw0rd', db='aiopms') #使用cursor()方法建立一個遊標物件cu #方式一,返回元組巢狀元組 cu=c.cursor() # #執行結果:((1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,)) #方式二,返回列表巢狀字典 # cu=c.cursor(cursor=pymysql.cursors.DictCursor) #執行結果:[{'sortid': 1}, {'sortid': 2}, {'sortid': 3}, {'sortid': 4}, {'sortid': 5}, {'sortid': 6}, {'sortid': 7}, {'sortid': 8}] #使用execute()方法執行sql查詢 cu.execute("select sortid from pms_knowledges_sort") #使用fetchall()方法獲取查詢結果 result=cu.fetchall() print(result) #關閉資料庫連線 c.close() #元組格式,取第一個值 1 print(result[0][0]) # #元組格式,取所有結果的值 for i in range(len(result)): print("第{}個的值:{}".format(i+1,result[i][0])) #結果 # 第1個的值:1 ... #字典格式,取第一個值 1 # print(result[0]["sortid"])
執行結果:
((1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,)) 1 第1個的值:1 第2個的值:2 第3個的值:3 第4個的值:4 第5個的值:5 第6個的值:6 第7個的值:7 第8個的值:8
如果想查詢結果以字典格式輸出,可以用c.cursor(cursor=pymysql.cursors.DictCursor)
c.cursor(),返回元組巢狀元組
刪除操作
使用python刪除一條資料,比如,刪除pms_users表中的xingzi這條記錄
delete from pms_users where username='xingzi'
# coding:utf-8 import pymysql #開啟資料庫連線 c=pymysql.connect(host='47.98.66.11', port=3306, user='root', password='P@ssw0rd', db='aiopms') #使用cursor()方法獲取操作遊標 cu=c.cursor() try: #執行 cu.execute("delete from pms_users where username='xingzi'") #提交 c.commit() except Exception as e: print("操作報錯:{}".format(e)) #錯誤回滾 c.rollback() finally: c.close()
更新操作
更新username使用者名稱是maomao的使用者,把status改成2
update pms_users set status=2 where username='maomao'
# coding:utf-8 import pymysql #連線資料庫 c=pymysql.connect(host='47.98.66.11', port=3306, user='root', passwd='P@ssw0rd', db='aiopms') #使用cursor()方法獲取操作遊標 cu=c.cursor() try: #執行sql cu.execute('update pms_users set status=2 where username="maomao"') c.commit() #提交 except Exception as e: print("執行報錯:{}".format(e)) c.rollback() #錯誤回滾 finally: c.close()
新增資料
往資料庫裡面插入一條資料,比如在pms_knowledges_sort表中插入一條資料
insert into pms_knowledges_sort values(9,"學習","",1)
# coding:utf-8 import pymysql #連線資料庫 c=pymysql.connect(host='47.98.66.11', port=3306, user='root', passwd='P@ssw0rd', db='aiopms' ) cu=c.cursor() try: cu.execute('insert into pms_knowledges_sort values(9,"學習","",1)') c.commit() except Exception as e: print("執行報錯:{}".format(e)) c.rollback() finally: c.close()
從上面的程式碼可以看出,處理查詢的程式碼不一樣,新增、刪除、更新資料庫操作程式碼都一樣,只是執行的sql不一樣。