1. 程式人生 > >Python使用pymql操作資料庫的增刪改查例項

Python使用pymql操作資料庫的增刪改查例項

Python使用pymql操作資料庫的增刪改查例項

資料庫:
在這裡插入圖片描述

一、新增:

import pymysql # 匯入pymysql包
conn=pymysql.connect(host='localhost',user='root',passwd='123',db='db_goods',port=3306,charset='utf8')
cur=conn.cursor()#獲取一個遊標
sql="INSERT INTO `tb_good`(`tb_name`,`tb_auto`,`tb_presie`) VALUE(%s,%s,%s)" # python的sql語句轉為符是:%s 。
data=cur.executemany(sql,[("《三毛流浪記》","三毛",15),("《小心流浪記》","三毛",15)]) # 多條語句插入,
# data = cur.execute(sql,("《三毛流浪記》","三毛",15)) #單條插入
conn.commit() # 提交
print(data) # 列印返回結果
cur.close() # 關閉遊標
conn.close() # 關閉連線

二、刪除:

import pymysql # 匯入pymysql包
conn=pymysql.connect(host='localhost',user='root',passwd='123',db='db_goods',port=3306,charset='utf8')
cur=conn.cursor()#獲取一個遊標
sql="delete from `tb_good` where `tb_id` = %s" # python的sql語句轉為符是:%s 。
data = cur.execute(sql,15) #執行
conn.commit() # 提交
print(data) # 列印返回結果
cur.close() # 關閉遊標
conn.close() # 關閉連線

三、修改:

import pymysql # 匯入pymysql包
conn=pymysql.connect(host='localhost',user='root',passwd='123',db='db_goods',port=3306,charset='utf8')
cur=conn.cursor()#獲取一個遊標
sql="UPDATE `tb_good` SET `tb_name` = %s WHERE `tb_id`=%s" # python的sql語句轉為符是:%s 。
data = cur.execute(sql,('《python操作資料庫》',15)) #執行
conn.commit() # 提交
print(data) # 列印返回結果
cur.close() # 關閉遊標
conn.close() # 關閉連線

四、查詢:

#匯入pymysql的包
import pymysql
try:
    #獲取一個數據庫連線,注意如果是UTF-8型別的,需要制定資料庫
    conn=pymysql.connect(host='localhost',user='root',passwd='123',db='db_goods',port=3306,charset='utf8')
    cur=conn.cursor()#獲取一個遊標
    sql="SELECT * FROM `tb_good` WHERE tb_id = %s"
    cur.execute(sql,15)
    data=cur.fetchall()
    for d in data :
        #注意int型別需要使用str函式轉義
        print("id: "+str(d[0])+'  名稱: '+d[1]+"  作者: "+d[2]+"  價格 :"+str(d[3]))
    cur.close()#關閉遊標
    conn.close()#釋放資料庫資源
except  Exception :print("查詢失敗")