首先安裝所需 插件
pip install mysql-connector-python

Import 剛安裝的插件
import mysql.connector
from mysql.connector import Error
之後可以試登入,最主要改host/database_name/username 和passowrd
try:
connection = mysql.connector.connect(host=’localhost’,
database=’database_name’,
user=’username’,
password=’password’)
你的SQL 語句可以在cursor.execute更改。
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")