Python操作MySQL數(shù)據(jù)庫的入門指南
在本篇技術博客中,我們將探討如何使用Python操作MySQL數(shù)據(jù)庫。我們將首先介紹如何建立連接,然后展示如何執(zhí)行基本的數(shù)據(jù)庫操作(如創(chuàng)建表、插入數(shù)據(jù)、查詢數(shù)據(jù)等)。最后,我們將通過一個詳細的代碼案例來鞏固所學內容。
1. 簡介
MySQL是一種關系型數(shù)據(jù)庫管理系統(tǒng),廣泛應用于各種應用程序和網站。Python提供了多種庫來與MySQL數(shù)據(jù)庫進行交互,本文將使用官方推薦的mysql-connector-python庫。
2. 安裝MySQL Connector
在開始之前,確保已經安裝了mysql-connector-python庫。如果尚未安裝,可以使用以下命令進行安裝:
pip install mysql-connector-python
3. 建立連接
為了與MySQL數(shù)據(jù)庫進行交互,我們首先需要建立連接。以下代碼展示了如何使用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服務器后,我們可以創(chuàng)建一個新的數(shù)據(jù)庫。以下代碼展示了如何使用CREATE DATABASE語句創(chuàng)建一個名為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)建一個名為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. 詳細代碼案例
在本節(jié)中,我們將通過一個實際案例來鞏固前面所學的內容。我們將創(chuà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. 總結
在本篇博客中,我們學習了如何使用Python操作MySQL數(shù)據(jù)庫。我們討論了如何建立連接、創(chuàng)建數(shù)據(jù)庫和表、插入數(shù)據(jù)、查詢數(shù)據(jù)、更新數(shù)據(jù)以及刪除數(shù)據(jù)。最后,通過一個詳細的代碼案例來鞏固所學知識。
如果你想深入了解mysql-connector-python庫的其他功能,請查閱官方文檔:MySQL Connector/Python Developer Guide。
以上就是Python操作MySQL數(shù)據(jù)庫的入門指南的詳細內容,更多關于Python操作MySQL的資料請關注腳本之家其它相關文章!
相關文章
Python?pandas刪除指定行/列數(shù)據(jù)的方法實例
這篇文章主要給大家介紹了關于Python?pandas刪除指定行/列數(shù)據(jù)的相關資料,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2022-01-01

