MySQL Connector/Python 開發人員指南  /  Connector/Python 連線建立  /  Connector/Python 選項檔支援

7.2 Connector/Python 選項檔支援

從 2.0.0 版開始,Connector/Python 能夠從選項檔讀取選項。(關於 MySQL 中選項檔的一般資訊,請參閱使用選項檔。)connect() 呼叫的兩個引數控制 Connector/Python 程式中選項檔的使用

  • option_files:要讀取的選項檔。該值可以是檔案路徑名稱(字串)或一系列路徑名稱字串。預設情況下,Connector/Python 不讀取任何選項檔,因此必須明確給定此引數才會讀取選項檔。檔案按照指定的順序讀取。

  • option_groups:如果讀取選項檔,則從選項檔中讀取哪些群組。該值可以是選項群組名稱(字串)或一系列群組名稱字串。如果未給定此引數,則預設值為 ['client', 'connector_python'],以讀取 [client][connector_python] 群組。

Connector/Python 還支援選項檔內的 !include!includedir 包含指令。這些指令的工作方式與其他 MySQL 程式相同(請參閱使用選項檔)。

此範例將單個選項檔指定為字串

cnx = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf')

此範例將多個選項檔指定為一系列字串

mysql_option_files = [
    '/etc/mysql/connectors.cnf',
    './development.cnf',
]
cnx = mysql.connector.connect(option_files=mysql_option_files)

預設情況下,Connector/Python 不讀取任何選項檔,以與 2.0.0 之前的版本向後相容。這與標準 MySQL 用戶端(例如 mysqlmysqldump)不同,這些用戶端預設會讀取選項檔。若要找出標準用戶端在您的系統上讀取哪些選項檔,請使用其 --help 選項來呼叫其中一個選項檔,並檢查輸出。例如

$> mysql --help
...
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/mysql/etc/my.cnf ~/.my.cnf
...

如果您指定 option_files 連線引數以讀取選項檔,則 Connector/Python 預設會讀取 [client][connector_python] 選項群組。若要明確指定要讀取的群組,請使用 option_groups 連線引數。以下範例只會讀取 [connector_python] 群組

cnx = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf',
                              option_groups='connector_python')

connect() 呼叫中指定的其他連線引數優先於從選項檔讀取的選項。假設 /etc/mysql/connectors.conf 包含以下行

[client]
database=cpyapp

以下 connect() 呼叫不包含任何 database 連線引數。產生的連線會使用選項檔中指定的資料庫 cpyapp

cnx = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf')

相反地,以下 connect() 呼叫指定與選項檔中找到的預設資料庫不同的預設資料庫。產生的連線會使用 cpyapp_dev 作為預設資料庫,而不是 cpyapp

cnx2 = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf',
                               database='cpyapp_dev')

如果無法讀取選項檔或已讀取選項檔,Connector/Python 會引發 ValueError。這包括透過包含指令讀取的檔案。

對於 [connector_python] 群組,只接受 Connector/Python 支援的選項。無法識別的選項會導致引發 ValueError

對於其他選項群組,Connector/Python 會忽略無法識別的選項。

具名的選項群組不存在不是錯誤。

Connector/Python 會將選項檔中的選項值視為字串,並使用 eval() 評估它們。這使得可以指定比簡單純量更複雜的選項值。