要連接MySQL數(shù)據(jù)庫,首先需要安裝MySQL數(shù)據(jù)庫驅(qū)動(dòng)程序。在Python中,可以使用pymysql
或mysql-connector-python
等庫來連接MySQL數(shù)據(jù)庫。
以下是使用pymysql
庫連接MySQL數(shù)據(jù)庫的步驟:
安裝pymysql
庫:
pip install pymysql
導(dǎo)入pymysql
庫:
import pymysql
建立數(shù)據(jù)庫連接:
conn = pymysql.connect(
host='localhost', # 數(shù)據(jù)庫主機(jī)地址
port=3306, # 數(shù)據(jù)庫端口號(hào),默認(rèn)為3306
user='root', # 數(shù)據(jù)庫用戶名
password='password', # 數(shù)據(jù)庫密碼
db='database_name', # 數(shù)據(jù)庫名
charset='utf8mb4', # 字符集
cursorclass=pymysql.cursors.DictCursor # 游標(biāo)類型,這里使用字典類型的游標(biāo)
)
創(chuàng)建游標(biāo)對(duì)象:
cursor = conn.cursor()
執(zhí)行SQL查詢:
cursor.execute("SELECT * FROM table_name")
result = cursor.fetchall()
關(guān)閉游標(biāo)和數(shù)據(jù)庫連接:
cursor.close()
conn.close()
這樣就可以連接上MySQL數(shù)據(jù)庫并執(zhí)行SQL查詢了。根據(jù)具體的需求,可以進(jìn)一步根據(jù)pymysql
庫提供的方法來插入、更新、刪除數(shù)據(jù)等操作。