Python實現mysql數據庫增刪改查


 利用python操作mysql數據庫用法簡單,環境配置容易,本文將實現對庫增、刪、改、查的簡易封裝!

 

  1. 環境配置

  安裝第三方包  ,導入模塊 mysql.connector 

pip install mysql-connector
2.使用說明

  本文將提供add,delete,update,query以及connect五種方法,下邊將詳述使用參數:

方法名 描述 傳入參數 return
connect
創建鏈接數據庫*
opt:用戶可傳入自定義數據庫鏈接信息
{'host':'','user':'','password':'','port':'','database':'','charset':''}
返回鏈接connect
add
 插入
mydb:創建的鏈接connent;
sql:sql插入、更新語句
# sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
# sql = "UPDATE sites SET name = %s WHERE name = %s"
val:插入、更新的值
# val = ("RUNOOB", "https://www.runoob.com")
# val = ("Zhihu", "ZH")
 
無  
update   更新
delete   刪除  
mydb,sql
 
query   查詢   list
說明:首先建立鏈接,其次再將獲取到的鏈接進行數據庫增刪改查
3.源代碼

  
# coding=utf-8
import mysql.connector #先安裝mysql-connector-python-1.0.12-py3.3,再引入包  pip install mysql-connector

#創建鏈接數據庫
def connect(opt):
    config={'host':opt['host'] or '127.0.0.1',#默認127.0.0.1
            'user':opt['user'] or 'root',
            'password':opt['password'] or 'root',
            'port':opt['port'] or 3306,#默認即為3306
            'database':opt['database'] or 'hibernate',
            'charset':opt['charset'] or 'utf8'#默認即為utf8
            }
    try:
        mydb=mysql.connector.connect(**config)#connect方法加載config的配置進行數據庫的連接,完成后用一個變量進行接收
    except mysql.connector.Error as e:
        print('數據庫鏈接失敗!',str(e))
    else:#try沒有異常的時候才會執行
        print("數據庫連接sucessfully!")
        return mydb

    # 插入
    # sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
    # val = ("RUNOOB", "https://www.runoob.com")
def add(mydb,sql,val):
    mycursor = mydb.cursor()
    mycursor.execute(sql, val)
    mydb.commit()    # 數據表內容有更新,必須使用到該語句
    print(mycursor.rowcount, "記錄插入成功。")

    # 更新
    # sql = "UPDATE sites SET name = %s WHERE name = %s"
    # val = ("Zhihu", "ZH")
def update(mydb,sql,val):
    mycursor = mydb.cursor()
    mycursor.execute(sql, val)
    mydb.commit()
    print(mycursor.rowcount, " 條記錄被修改")

    # 查詢
    # sql="SELECT * FROM sites"
def query(mydb,sql):
    mycursor = mydb.cursor()
    mycursor.execute(sql)
    myresult = mycursor.fetchall()     # fetchall() 獲取所有記錄
    for x in myresult:
        print(x)
    return myresult

    # 刪除
    # sql = "DELETE FROM sites WHERE name = 'stackoverflow'"
def delete(mydb,sql):
    mycursor = mydb.cursor()
    mycursor.execute(sql)
    mydb.commit()
    print(mycursor.rowcount, " 條記錄刪除")

  

 


免責聲明!

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



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