TShopping

 找回密碼
 註冊
搜索
查看: 1574|回復: 0
打印 上一主題 下一主題

[教學] Python 使用 MySQL Connector 操作 MySQL/MariaDB 資料庫教學與範例

[複製鏈接]
跳轉到指定樓層
1#
發表於 2022-4-6 12:46:20 | 只看該作者 |只看大圖 回帖獎勵 |倒序瀏覽 |閱讀模式
 
Push to Facebook

介紹如何使用 Python 的 MySQL Connector 模組連接 MySQL/MariaDB 資料庫,進行查詢、新增或刪除等各種操作。



Python 有許多 MySQL/MariaDB 資料庫相關的模組,而最常被使用的就是 MySQL Connector 與 MySQLdb 這兩個模組,以下是 MySQL Connector 模組的使用方式。
安裝 MySQL Connector 模組
開啟 Windows 中的命令提示自元,使用 pip 安裝 Python 的 MySQL Connector 模組:

  1. pip install mysql-connector-python
複製代碼

安裝 Python 的 MySQL Connector 模組
安裝 Python 的 MySQL Connector 模組
安裝好之後,就可以開始使用了 Python 的 MySQL Connector 模組。

連接資料庫
以下是使用 MySQL Connector 模組連接資料庫的範例:

  1. import mysql.connector
  2. from mysql.connector import Error

  3. try:
  4.     # 連接 MySQL/MariaDB 資料庫
  5.     connection = mysql.connector.connect(
  6.         host='localhost',          # 主機名稱
  7.         database='officeguide_db', # 資料庫名稱
  8.         user='officeguide',        # 帳號
  9.         password='your_password')  # 密碼

  10.     if connection.is_connected():

  11.         # 顯示資料庫版本
  12.         db_Info = connection.get_server_info()
  13.         print("資料庫版本:", db_Info)

  14.         # 顯示目前使用的資料庫
  15.         cursor = connection.cursor()
  16.         cursor.execute("SELECT DATABASE();")
  17.         record = cursor.fetchone()
  18.         print("目前使用的資料庫:", record)

  19. except Error as e:
  20.     print("資料庫連接失敗:", e)

  21. finally:
  22.     if (connection.is_connected()):
  23.         cursor.close()
  24.         connection.close()
  25.         print("資料庫連線已關閉")
複製代碼

資料庫版本: 5.5.5-10.4.8-MariaDB
目前使用的資料庫: ('officeguide_db',)
資料庫連線已關閉


查詢資料
以下是使用 SELECT 查詢資料的範例:

  1. import mysql.connector
  2. from mysql.connector import Error

  3. try:
  4.     # 連接 MySQL/MariaDB 資料庫
  5.     connection = mysql.connector.connect(
  6.         host='localhost',          # 主機名稱
  7.         database='officeguide_db', # 資料庫名稱
  8.         user='officeguide',        # 帳號
  9.         password='your_password')  # 密碼

  10.     # 查詢資料庫
  11.     cursor = connection.cursor()
  12.     cursor.execute("SELECT name, age FROM persons;")

  13.     # 列出查詢的資料
  14.     for (name, age) in cursor:
  15.         print("Name: %s, Age: %d" % (name, age))


  16. except Error as e:
  17.     print("資料庫連接失敗:", e)

  18. finally:
  19.     if (connection.is_connected()):
  20.         cursor.close()
  21.         connection.close()
  22.         print("資料庫連線已關閉")
複製代碼

Name: Arden, Age: 32
Name: Bond, Age: 54
Name: Cole, Age: 12
Name: Dana, Age: 19
資料庫連線已關閉

也可以使用 fetchall 將資料一次全部抓到 Python 中再處理:

  1. import mysql.connector
  2. from mysql.connector import Error

  3. try:
  4.     # 連接 MySQL/MariaDB 資料庫
  5.     connection = mysql.connector.connect(
  6.         host='localhost',          # 主機名稱
  7.         database='officeguide_db', # 資料庫名稱
  8.         user='officeguide',        # 帳號
  9.         password='your_password')  # 密碼

  10.     # 查詢資料庫
  11.     cursor = connection.cursor()
  12.     cursor.execute("SELECT name, age FROM persons;")

  13.     # 取回全部的資料
  14.     records = cursor.fetchall()
  15.     print("資料筆數:", cursor.rowcount)

  16.     # 列出查詢的資料
  17.     for (name, age) in records:
  18.         print("Name: %s, Age: %d" % (name, age))

  19. except Error as e:
  20.     print("資料庫連接失敗:", e)

  21. finally:
  22.     if (connection.is_connected()):
  23.         cursor.close()
  24.         connection.close()
  25.         print("資料庫連線已關閉")
複製代碼

資料筆數: 4
Name: Arden, Age: 32
Name: Bond, Age: 54
Name: Cole, Age: 12
Name: Dana, Age: 19
資料庫連線已關閉


新增資料
以下是使用 INSERT 新增資料的範例:

  1. import mysql.connector
  2. from mysql.connector import Error

  3. try:
  4.     # 連接 MySQL/MariaDB 資料庫
  5.     connection = mysql.connector.connect(
  6.         host='localhost',          # 主機名稱
  7.         database='officeguide_db', # 資料庫名稱
  8.         user='officeguide',        # 帳號
  9.         password='your_password')  # 密碼

  10.     # 新增資料
  11.     sql = "INSERT INTO persons (name, age, city) VALUES (%s, %s, %s);"
  12.     new_data = ("Jack", 13, "Kaohsiung")
  13.     cursor = connection.cursor()
  14.     cursor.execute(sql, new_data)

  15.     # 確認資料有存入資料庫
  16.     connection.commit()

  17. except Error as e:
  18.     print("資料庫連接失敗:", e)

  19. finally:
  20.     if (connection.is_connected()):
  21.         cursor.close()
  22.         connection.close()
複製代碼

修改資料
以下是使用 UPDATE 更新資料的範例:

  1. import mysql.connector
  2. from mysql.connector import Error

  3. try:
  4.     # 連接 MySQL/MariaDB 資料庫
  5.     connection = mysql.connector.connect(
  6.         host='localhost',          # 主機名稱
  7.         database='officeguide_db', # 資料庫名稱
  8.         user='officeguide',        # 帳號
  9.         password='your_password')  # 密碼

  10.     # 更新資料
  11.     sql = "UPDATE persons SET age = %s WHERE id = %s;"
  12.     cursor = connection.cursor()
  13.     cursor.execute(sql, (27, 6))

  14.     # 確認資料有存入資料庫
  15.     connection.commit()

  16. except Error as e:
  17.     print("資料庫連接失敗:", e)

  18. finally:
  19.     if (connection.is_connected()):
  20.         cursor.close()
  21.         connection.close()
複製代碼

刪除資料
以下是使用 DELETE 刪除資料的範例:

  1. import mysql.connector
  2. from mysql.connector import Error

  3. try:
  4.     # 連接 MySQL/MariaDB 資料庫
  5.     connection = mysql.connector.connect(
  6.         host='localhost',          # 主機名稱
  7.         database='officeguide_db', # 資料庫名稱
  8.         user='officeguide',        # 帳號
  9.         password='your_password')  # 密碼

  10.     # 更新資料
  11.     sql = "DELETE FROM persons WHERE id = %s;"
  12.     cursor = connection.cursor()
  13.     cursor.execute(sql, (6,))

  14.     # 確認資料有存入資料庫
  15.     connection.commit()

  16. except Error as e:
  17.     print("資料庫連接失敗:", e)

  18. finally:
  19.     if (connection.is_connected()):
  20.         cursor.close()
  21.         connection.close()
複製代碼

參考資料:MySQL 官方文件、pynative

https://officeguide.cc/python-mysql-mariadb-database-connector-tutorial-examples/

 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-4-26 15:34 , Processed in 0.049018 second(s), 25 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表