MySQL Connector/Python 開發人員指南  /  Connector/Python 程式碼範例  /  使用 Connector/Python 連接 MySQL

5.1 使用 Connector/Python 連接 MySQL

connect() 建構函式會建立與 MySQL 伺服器的連線,並傳回 MySQLConnection 物件。

以下範例示範如何連線至 MySQL 伺服器

import mysql.connector

cnx = mysql.connector.connect(user='scott', password='password',
                              host='127.0.0.1',
                              database='employees')
cnx.close()

第 7.1 節, 「Connector/Python 連線引數」 說明允許的連線引數。

也可以使用 connection.MySQLConnection() 類別建立連線物件

from mysql.connector import (connection)

cnx = connection.MySQLConnection(user='scott', password='password',
                                 host='127.0.0.1',
                                 database='employees')
cnx.close()

兩種形式(使用 connect() 建構函式或直接使用類別)都是有效且功能相等的,但建議使用 connect(),並且本手冊中的大多數範例都使用它。

若要處理連線錯誤,請使用 try 陳述式,並使用 errors.Error 例外捕捉所有錯誤

import mysql.connector
from mysql.connector import errorcode

try:
  cnx = mysql.connector.connect(user='scott',
                                database='employ')
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with your user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  cnx.close()

在字典中定義連線引數並使用 ** 運算子是另一種選項

import mysql.connector

config = {
  'user': 'scott',
  'password': 'password',
  'host': '127.0.0.1',
  'database': 'employees',
  'raise_on_warnings': True
}

cnx = mysql.connector.connect(**config)

cnx.close()

定義記錄器選項、重新連線常式,並定義為名為 connect_to_mysql 的連線方法

import logging
import time
import mysql.connector

# Set up logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

# Log to console
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)

# Also log to a file
file_handler = logging.FileHandler("cpy-errors.log")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler) 

def connect_to_mysql(config, attempts=3, delay=2):
    attempt = 1
    # Implement a reconnection routine
    while attempt < attempts + 1:
        try:
            return mysql.connector.connect(**config)
        except (mysql.connector.Error, IOError) as err:
            if (attempts is attempt):
                # Attempts to reconnect failed; returning None
                logger.info("Failed to connect, exiting without a connection: %s", err)
                return None
            logger.info(
                "Connection failed: %s. Retrying (%d/%d)...",
                err,
                attempt,
                attempts-1,
            )
            # progressive reconnect delay
            time.sleep(delay ** attempt)
            attempt += 1
    return None

使用上述常式連接並使用 Sakila 資料庫,假設它定義在名為 myconnection.py 的檔案中

from myconnection import connect_to_mysql

config = {
    "host": "127.0.0.1",
    "user": "user",
    "password": "pass",
    "database": "sakila",
}

cnx = connect_to_mysql(config, attempts=3)

if cnx and cnx.is_connected():

    with cnx.cursor() as cursor:

        result = cursor.execute("SELECT * FROM actor LIMIT 5")

        rows = cursor.fetchall()

        for rows in rows:

            print(rows)

    cnx.close()

else:

    print("Could not connect")

使用 Connector/Python Python 或 C 擴充功能

Connector/Python 提供兩種實作:純 Python 介面和使用 MySQL C 用戶端程式庫的 C 擴充功能 (請參閱 第 8 章,Connector/Python C 擴充功能)。這可以在執行時使用 use_pure 連線引數進行設定。從 MySQL 8 開始,預設值為 False,表示使用 C 擴充功能。如果系統上沒有 C 擴充功能,則 use_pure 預設為 True。設定 use_pure=False 會導致連線在您的 Connector/Python 安裝包含 C 擴充功能時使用它,而 use_pure=TrueFalse 表示如果有的話,則使用 Python 實作。

注意

use_pure 選項和 C 擴充功能是在 Connector/Python 2.1.1 中新增的。

以下範例示範如何將 use_pure 設定為 False。

import mysql.connector

cnx = mysql.connector.connect(user='scott', password='password',
                              host='127.0.0.1',
                              database='employees',
                              use_pure=False)
cnx.close()

也可以透過匯入 _mysql_connector 模組而不是 mysql.connector 模組直接使用 C 擴充功能。如需更多資訊,請參閱第 8.2 節,「_mysql_connector C 擴充功能模組」