Python操作MySQL數(shù)據(jù)庫的入門指南
在本篇技術(shù)博客中,我們將探討如何使用Python操作MySQL數(shù)據(jù)庫。我們將首先介紹如何建立連接,然后展示如何執(zhí)行基本的數(shù)據(jù)庫操作(如創(chuàng)建表、插入數(shù)據(jù)、查詢數(shù)據(jù)等)。最后,我們將通過一個(gè)詳細(xì)的代碼案例來鞏固所學(xué)內(nèi)容。
1. 簡介
MySQL是一種關(guān)系型數(shù)據(jù)庫管理系統(tǒng),廣泛應(yīng)用于各種應(yīng)用程序和網(wǎng)站。Python提供了多種庫來與MySQL數(shù)據(jù)庫進(jìn)行交互,本文將使用官方推薦的mysql-connector-python庫。
2. 安裝MySQL Connector
在開始之前,確保已經(jīng)安裝了mysql-connector-python庫。如果尚未安裝,可以使用以下命令進(jìn)行安裝:
pip install mysql-connector-python
3. 建立連接
為了與MySQL數(shù)據(jù)庫進(jìn)行交互,我們首先需要建立連接。以下代碼展示了如何使用mysql.connector.connect()方法建立連接:
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password"
)
print("Connected to MySQL server!")
cnx.close()4. 創(chuàng)建數(shù)據(jù)庫
連接到MySQL服務(wù)器后,我們可以創(chuàng)建一個(gè)新的數(shù)據(jù)庫。以下代碼展示了如何使用CREATE DATABASE語句創(chuàng)建一個(gè)名為mydb的數(shù)據(jù)庫:
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password"
)
cursor = cnx.cursor()
cursor.execute("CREATE DATABASE mydb")
print("Database 'mydb' created!")
cnx.close()5. 創(chuàng)建表
創(chuàng)建數(shù)據(jù)庫后,我們需要在其中創(chuàng)建表。以下代碼展示了如何創(chuàng)建一個(gè)名為users的表,并為其添加id、name和email列:
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
cursor = cnx.cursor()
cursor.execute("""
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
)
""")
print("Table 'users' created!")
cnx.close()6. 插入數(shù)據(jù)
創(chuàng)建表后,我們可以向其中插入數(shù)據(jù)。以下代碼展示了如何向users表插入一條數(shù)據(jù):
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
cursor = cnx.cursor()
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
val = ("John Doe", "john.doe@example.com")
cursor.execute(sql, val)
cnx.commit()
print(f"{cursor.rowcount} record(s) inserted!")
cnx.close()7. 查詢數(shù)據(jù)
我們可以使用SELECT語句從表中查詢數(shù)據(jù)。以下代碼展示了如何從users表中查詢所有數(shù)據(jù):
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
cursor = cnx.cursor()
cursor.execute("SELECT * FROM users")
for row in cursor.fetchall():
print(row)
cnx.close()8. 更新數(shù)據(jù)
要更新表中的數(shù)據(jù),我們可以使用UPDATE語句。以下代碼展示了如何更新users表中的一條數(shù)據(jù):
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
cursor = cnx.cursor()
sql = "UPDATE users SET email = %s WHERE name = %s"
val = ("john.doe@newexample.com", "John Doe")
cursor.execute(sql, val)
cnx.commit()
print(f"{cursor.rowcount} record(s) updated!")
cnx.close()9. 刪除數(shù)據(jù)
要從表中刪除數(shù)據(jù),我們可以使用DELETE語句。以下代碼展示了如何從users表中刪除一條數(shù)據(jù):
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
cursor = cnx.cursor()
sql = "DELETE FROM users WHERE name = %s"
val = ("John Doe",)
cursor.execute(sql, val)
cnx.commit()
print(f"{cursor.rowcount} record(s) deleted!")
cnx.close()10. 詳細(xì)代碼案例
在本節(jié)中,我們將通過一個(gè)實(shí)際案例來鞏固前面所學(xué)的內(nèi)容。我們將創(chuàng)建一個(gè)簡單的應(yīng)用程序,該程序可以將用戶信息添加到數(shù)據(jù)庫中,并根據(jù)需要查詢、更新或刪除這些信息。
import mysql.connector
def connect_to_db():
return mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
def create_user(name, email):
cnx = connect_to_db()
cursor = cnx.cursor()
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
val = (name, email)
cursor.execute(sql, val)
cnx.commit()
cnx.close()
def get_all_users():
cnx = connect_to_db()
cursor = cnx.cursor()
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
cnx.close()
return result
def update_user_email(name, new_email):
cnx = connect_to_db()
cursor = cnx.cursor()
sql = "UPDATE users SET email = %s WHERE name = %s"
val = (new_email, name)
cursor.execute(sql, val)
cnx.commit()
cnx.close()
def delete_user(name):
cnx = connect_to_db()
cursor = cnx.cursor()
sql = "DELETE FROM users WHERE name = %s"
val = (name,)
cursor.execute(sql, val)
cnx.commit()
cnx.close()
# 添加用戶
create_user("Alice", "alice@example.com")
create_user("Bob", "bob@example.com")
# 查詢所有用戶
users = get_all_users()
print("All users:")
for user in users:
print(user)
# 更新用戶郵箱
update_user_email("Alice", "alice@newexample.com")
# 查詢所有用戶
users = get_all_users()
print("All users after update:")
for user in users:
print(user)
# 刪除用戶
delete_user("Bob")
# 查詢所有用戶
users = get_all_users()
print("All users after deletion:")
for user in users:
print(user)11. 總結(jié)
在本篇博客中,我們學(xué)習(xí)了如何使用Python操作MySQL數(shù)據(jù)庫。我們討論了如何建立連接、創(chuàng)建數(shù)據(jù)庫和表、插入數(shù)據(jù)、查詢數(shù)據(jù)、更新數(shù)據(jù)以及刪除數(shù)據(jù)。最后,通過一個(gè)詳細(xì)的代碼案例來鞏固所學(xué)知識(shí)。
如果你想深入了解mysql-connector-python庫的其他功能,請查閱官方文檔:MySQL Connector/Python Developer Guide。
以上就是Python操作MySQL數(shù)據(jù)庫的入門指南的詳細(xì)內(nèi)容,更多關(guān)于Python操作MySQL的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
關(guān)于如何把Python對象存儲(chǔ)為文件的方法詳解
本文將給大家介紹如何把Python對象存儲(chǔ)為文件的方法,pickle可以用二進(jìn)制表示并讀寫python數(shù)據(jù),這個(gè)功能并不安全,如果把一個(gè)pickle暴露給別人,有被植入惡意程序的風(fēng)險(xiǎn),文中通過代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2024-01-01
Python使用sort()方法對數(shù)組進(jìn)行排序的操作指南
在開發(fā)過程中,經(jīng)常需要對數(shù)據(jù)進(jìn)行排序,Python 中的 sort() 方法是用來對列表進(jìn)行排序的,它是一個(gè)非常常用且高效的排序工具,本文將通過一個(gè)實(shí)際項(xiàng)目的代碼示例,來講解如何使用 sort() 方法對數(shù)組進(jìn)行排序,需要的朋友可以參考下2025-06-06
使用Python實(shí)現(xiàn)Flutter項(xiàng)目的自動(dòng)化構(gòu)建與發(fā)布
本文介紹了作者為解決移動(dòng)端Flutter應(yīng)用開發(fā)中構(gòu)建、上傳和通知的繁瑣問題,使用Python編寫的一套自動(dòng)化腳本,該腳本實(shí)現(xiàn)了自動(dòng)構(gòu)建、上傳到蒲公英測試平臺(tái)、發(fā)送郵件通知等功能,顯著提高了開發(fā)效率,需要的朋友可以參考下2026-02-02
解決pytorch GPU 計(jì)算過程中出現(xiàn)內(nèi)存耗盡的問題
今天小編就為大家分享一篇解決pytorch GPU 計(jì)算過程中出現(xiàn)內(nèi)存耗盡的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
matplotlib圖例legend語法及設(shè)置的方法
這篇文章主要介紹了matplotlib圖例legend語法及設(shè)置的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
Python實(shí)現(xiàn)檢測文件是否存在的方法完整指南
Python作為一門強(qiáng)大的編程語言,提供了多種方法來檢測文件存在性,本文將深入探討Python中文件存在性檢測的各種方法,大家可以根據(jù)需要進(jìn)行選擇2025-09-09
Python多線程編程(八):使用Event實(shí)現(xiàn)線程間通信
這篇文章主要介紹了Python多線程編程(八):使用Event實(shí)現(xiàn)線程間通信,,需要的朋友可以參考下2015-04-04

