Python MySQL - 資料庫連線



連線MySQL的一種方法是,像下面這樣開啟你係統中的MySQL命令提示符:

MySQL Command Prompt

這裡會要求輸入密碼;你需要輸入你在安裝時為預設使用者(root)設定的密碼。

然後將建立與MySQL的連線,並顯示以下訊息:

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.12-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

你可以在任何時候使用mysql>提示符下的exit命令斷開與MySQL資料庫的連線。

mysql> exit
Bye

使用python建立與MySQL的連線

在使用python建立與MySQL資料庫的連線之前,假設:

  • 我們已經建立了一個名為mydb的資料庫。

  • 我們已經建立了一個名為EMPLOYEE的表,其列為FIRST_NAME、LAST_NAME、AGE、SEX和INCOME。

  • 我們用來連線MySQL的憑據是使用者名稱:root,密碼:password

你可以使用connect()建構函式建立連線。它接受使用者名稱、密碼、主機和需要連線的資料庫名稱(可選),並返回一個MySQLConnection類的物件。

示例

以下是連線MySQL資料庫“mydb”的示例。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Executing an MYSQL function using the execute() method
cursor.execute("SELECT DATABASE()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)

#Closing the connection
conn.close()

輸出

執行此指令碼後,將產生以下輸出:

D:\Python_MySQL>python EstablishCon.py
Connection established to: ('mydb',)

你也可以透過將憑據(使用者名稱、密碼、主機名和資料庫名稱)傳遞給connection.MySQLConnection()來建立與MySQL的連線,如下所示:

from mysql.connector import (connection)

#establishing the connection
conn = connection.MySQLConnection(user='root', password='password', host='127.0.0.1', database='mydb')

#Closing the connection
conn.close()
廣告