MySQL是一種開源的關係型資料庫,廣泛應用於Web應用程序的開發中。Python是一種功能強大的高級編程語言,因其簡單易用而備受好評。在數據交互方面,Python與MySQL的組合尤為強大,提供了眾多高效的數據交互方案。本文將深入探討Python與MySQL的高效數據交互方案,包括連接資料庫、增刪改查數據及數據備份等幾個方面。
一、連接MySQL資料庫
要與MySQL資料庫進行交互,首先需要連接到MySQL伺服器。Python提供了多種方法來連接到MySQL資料庫,以下是其中的一些方法:
1. 使用PyMySQL庫連接MySQL資料庫:
import pymysql
# 打開資料庫連接
db = pymysql.connect("localhost","testuser","test123","testdb" )
# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()
# 使用 execute() 方法執行 SQL 查詢
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法獲取單條數據.
data = cursor.fetchone()
print ("Database version : %s " % data)
# 關閉資料庫連接
db.close()
2. 使用MySQLdb庫連接MySQL資料庫:
import MySQLdb
# 打開資料庫連接
db = MySQLdb.connect("localhost","testuser","test123","testdb" )
# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()
# 使用 execute() 方法執行 SQL 查詢
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法獲取單條數據.
data = cursor.fetchone()
print ("Database version : %s " % data)
# 關閉資料庫連接
db.close()
3. 使用mysql-connector-python庫連接MySQL資料庫:
import mysql.connector
# 打開資料庫連接
db = mysql.connector.connect(
host="localhost",
user="testuser",
passwd="test123",
database="testdb"
)
# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()
# 使用 execute() 方法執行 SQL 查詢
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法獲取單條數據.
data = cursor.fetchone()
print ("Database version : %s " % data)
# 關閉資料庫連接
db.close()
二、增刪改查數據
連接到MySQL資料庫後,接下來的一步是執行SQL查詢、插入、更新和刪除數據等操作。以下是Python代碼示例。
1. 查詢數據:
import mysql.connector
# 打開資料庫連接
db = mysql.connector.connect(
host="localhost",
user="testuser",
passwd="test123",
database="testdb"
)
# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()
# 查詢數據
cursor.execute("SELECT * FROM EMPLOYEE")
# 獲取所有記錄列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 列印結果
print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income ))
# 關閉資料庫連接
db.close()
2. 插入數據:
import mysql.connector
# 打開資料庫連接
db = mysql.connector.connect(
host="localhost",
user="testuser",
passwd="test123",
database="testdb"
)
# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()
# 插入數據
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (%s, %s, %s, %s, %s)"
val = ("John", "Doe", 25, "Male", 2000)
cursor.execute(sql, val)
db.commit()
# 列印插入成功的數據ID
print("插入成功,插入的數據ID為:", cursor.lastrowid)
# 關閉資料庫連接
db.close()
3. 修改數據:
import mysql.connector
# 打開資料庫連接
db = mysql.connector.connect(
host="localhost",
user="testuser",
passwd="test123",
database="testdb"
)
# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()
# 修改數據
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%s'" % ('Male')
cursor.execute(sql)
db.commit()
# 列印修改成功的數據條數
print("修改 %d 條數據" % cursor.rowcount)
# 關閉資料庫連接
db.close()
4. 刪除數據:
import mysql.connector
# 打開資料庫連接
db = mysql.connector.connect(
host="localhost",
user="testuser",
passwd="test123",
database="testdb"
)
# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()
# 刪除數據
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
cursor.execute(sql)
db.commit()
# 列印刪除成功的數據條數
print("刪除 %d 條數據" % cursor.rowcount)
# 關閉資料庫連接
db.close()
三、數據備份
在開發過程中,數據備份是必不可少的。以下是Python代碼示例。假設我們要將某個資料庫備份到一個.sql文件中。
import os
import time
import mysql.connector
# 需要備份的資料庫名稱
DB_NAME = 'testdb'
BACKUP_PATH = 'backup/'
# 備份函數
def backup():
'''備份資料庫'''
# 備份文件名
today = time.strftime('%Y%m%d')
file_name = DB_NAME + '_' + today + ".sql"
file_path = BACKUP_PATH + file_name
# 打開資料庫連接
db = mysql.connector.connect(
host="localhost",
user="testuser",
passwd="test123",
database=DB_NAME
)
# 使用資料庫游標
cursor = db.cursor()
# 執行命令
cmd = "mysqldump -u %s -p%s %s > %s" % ('root', '', DB_NAME, file_path)
os.system(cmd)
# 關閉游標和資料庫連接
cursor.close()
db.close()
print("Database backed up successfully")
print("Backup path: " + os.path.abspath(file_path))
if __name__ == "__main__":
backup()
此外,Python還提供了大量的第三方模塊,可以幫助我們更輕鬆地進行數據備份。
總結
本文深入探討了Python與MySQL的高效數據交互方案,包括連接資料庫、增刪改查數據及數據備份等幾個方面。希望讀者可以通過本文對Python與MySQL的數據交互方案有更深入的認識,並能夠根據實際需求使用相應的數據交互方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/288588.html