- Python & MySQL 教程
- Python & MySQL - 首頁
- Python & MySQL - 概述
- Python & MySQL - 環境搭建
- Python & MySQL 示例
- Python & MySQL - 連線資料庫
- Python & MySQL - 建立資料庫
- Python & MySQL - 刪除資料庫
- Python & MySQL - 選擇資料庫
- Python & MySQL - 建立表
- Python & MySQL - 刪除表
- Python & MySQL - 插入記錄
- Python & MySQL - 查詢記錄
- Python & MySQL - 更新記錄
- Python & MySQL - 刪除記錄
- Python & MySQL - Where 子句
- Python & MySQL - Like 子句
- Python & MySQL - 資料排序
- Python & MySQL - 使用連線
- Python & MySQL - 執行事務
- Python & MySQL - 處理錯誤
- Python & MySQL 有用資源
- Python & MySQL - 快速指南
- Python & MySQL - 有用資源
- Python & MySQL - 討論
Python & MySQL - 資料庫連線示例
Python MySQLdb 提供了 **MySQLdb.connect()** 函式來開啟資料庫連線。此函式接受多個引數,並返回一個連線物件以執行資料庫操作。
語法
db = MySQLdb.connect(host, username, passwd, dbName, port, socket);
| 序號 | 引數 & 描述 |
|---|---|
| 1 |
host 可選 - 執行資料庫伺服器的主機名。如果未指定,則預設值為 **localhost:3306**。 |
| 2 |
username 可選 - 訪問資料庫的使用者名稱。如果未指定,則預設為擁有伺服器程序的使用者名稱稱。 |
| 3 |
passwd 可選 - 訪問資料庫的使用者的密碼。如果未指定,則預設為空密碼。 |
| 4 |
dbName 可選 - 要執行查詢的資料庫名稱。 |
| 5 |
port 可選 - 要嘗試連線到 MySQL 伺服器的埠號。 |
| 6 |
socket 可選 - 應使用的套接字或命名管道。 |
還有其他幾個屬性。有關完整參考,請參閱 MySQLdb。
您可以隨時使用另一個連線物件函式 **close()** 斷開與 MySQL 資料庫的連線。
語法
db.close()
示例
嘗試以下示例連線到 MySQL 伺服器:
複製並貼上以下示例作為 mysql_example.py:
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","root","root@123")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
if data:
print('Version available: ', data)
else:
print('Version not retrieved.')
# disconnect from server
db.close()
輸出
使用 python 執行 mysql_example.py 指令碼並驗證輸出。
py mysql_example.py
Version available: ('8.0.23',)
廣告