# 連接到數據庫
> 原文: [https://thepythonguru.com/connecting-to-the-database/](https://thepythonguru.com/connecting-to-the-database/)
* * *
于 2020 年 1 月 7 日更新
* * *
在我們開始將數據庫與 python 一起使用之前,必須先連接到數據庫。 與 python 的數據庫通信分為四個階段:
1. 創建一個連接對象。
2. 創建一個游標對象以進行讀取/寫入。
3. 與數據庫進行交互。
4. 關閉連接。
**注意**:
我們將使用世界 mysql 數據庫,因此首先[下載](http://188.166.96.119/wp-content/uploads/2015/10/world.sql_.zip)并導入數據庫,如下所示:
首次登錄到您的 mysql 服務器
```py
mysql -u root -p
```
此時將要求您輸入密碼,輸入密碼,然后按`Enter`鍵。
```py
source path/to/world.sql
```
## 連接到數據庫
* * *
要連接到數據庫,您需要使用`connect()`方法。
**語法**:
```py
MySQLdb.connect(
host="127.0.0.1",
? ? ? ? ? ? ? ? user="username",
? ? ? ? ? ? ? ? passwd="password",
? ? ? ? ? ? ? ? db="database"
? ? ? ? ? ? ? ?)
```
成功后,`connect()`方法將返回一個連接對象。 否則,將引發`OperationalError`異常。
```py
from __future__ import print_function
import MySQLdb as my
db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)
print(db)
```
注意第一行`import print_function from __future__`中的`import`語句,這使我們能夠在 Python 2 中使用 Python 3 版本的`print()`函數。
**預期輸出**:
```py
<_mysql.connection open to '127.0.0.1' at 21fe6f0>
```
## 創建游標對象
* * *
開始與數據庫進行交互之前,需要創建游標對象。
**語法**:`connection_object.cursor()`
成功時,它將返回`Cursor`對象,否則將引發異常。
```py
from __future__ import print_function
import MySQLdb as my
db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)
print(db)
cursor = db.cursor()
print(cursor)
```
**預期輸出**:
```py
<_mysql.connection open to '127.0.0.1' at 239e2c0>
<MySQLdb.cursors.Cursor object at 0x02444AD0>
```
## 與數據庫交互
* * *
游標對象具有`execute()`方法,可用于執行 sql 查詢。
**語法**:`cursor.execute(sql)`
成功后,它將返回受影響的行數,否則將引發異常。
```py
from __future__ import print_function
import MySQLdb as my
db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)
print(db)
cursor = db.cursor()
number_of_rows = cursor.execute("select * from city");
print(number_of_rows)
```
**預期輸出**:
```py
4079
```
## 斷開連接
* * *
與數據庫進行交互之后,您需要關閉數據庫連接以放棄資源。
**語法**:`connection_object.close()`
```py
from __future__ import print_function
import MySQLdb as my
db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)
print(db)
cursor = db.cursor()
number_of_rows = cursor.execute("select * from city");
print(number_of_rows)
db.close()
```
現在您知道了如何與數據庫連接,執行查詢并關閉連接。 在下一篇文章中,我們討論如何[從表](/mysqldb-fetching-results/)中獲取行。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象