Python連線mysql資料庫及簡單增刪改查操作示例程式碼
阿新 • • 發佈:2020-08-06
1.安裝pymysql
進入cmd,輸入 pip install pymysql:
2.資料庫建表
在資料庫中,建立一個簡單的表,如圖:
3.簡單操作
3.1查詢操作
#coding=utf-8 #連線資料庫測試 import pymysql #開啟資料庫 db = pymysql.connect(host="localhost",user="root",password="root",db="test") #使用cursor()方法獲取操作遊標 cur = db.cursor() #查詢操作 sql = "select * from books" try: # 執行sql語句 cur.execute(sql) results = cur.fetchall() #遍歷結果 for rows in results: id = rows[0] name = rows[1] price = rows[2] bookcount = rows[3] author = rows[4] print("id: {},name: {},price: {},bookcount: {},author: {}".format(id,name,price,bookcount,author)) except Exception as e: raise e finally: db.close()
執行結果:
3.2插入操作
#coding=utf-8 #插入操作 import pymysql db = pymysql.connect(host="localhost",db="test") cur = db.cursor() sql = """insert into books(id,bookname,bookCount,author) values (4,'三體',20,3,'劉慈欣')""" try: cur.execute(sql) #提交 db.commit() except Exception as e: #錯誤回滾 db.rollback() finally: db.close()
執行結果:
3.3更新操作
#coding=utf-8 #更新操作 import pymysql db = pymysql.connect(host="localhost",db="test") # 使用cursor()方法獲取遊標 cur = db.cursor() sql_update = "update books set bookname = '%s',author = '%s' where id = %d" try: cur.execute(sql_update % ("邊城","沈從文",4)) #提交 db.commit() except Exception as e: #錯誤回滾 db.rollback() finally: db.close()
執行結果:
3.4刪除操作
#coding=utf-8 #刪除操作 import pymysql db = pymysql.connect(host="localhost",db="test") #使用cursor()獲取操作遊標 cur = db.cursor() sql_delete = "delete from books where id = %d" try: #向sql語句傳遞引數 cur.execute(sql_delete % (1)) #提交 db.commit() except Exception as e: #錯誤回滾 db.rollback() finally: db.close()
執行結果:
到此這篇關於Python連線mysql資料庫及簡單增刪改查操作示例程式碼的文章就介紹到這了,更多相關Python連線mysql資料庫及增刪改查操作內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!