>[info] 在python中,操作數據庫,是一件非常簡單的操作。我喜歡用PyMySQL庫來操作。
## 安裝 pymsql
```cmd
$ python3 -m pip install PyMySQL
```
## 使用示例
進行代碼演示前,我們先在數據庫中創建一個簡單的表。
```sql
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) COLLATE utf8_bin NOT NULL,
`password` varchar(255) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1 ;
```
下面是PyMySQL對數據庫的插入與查詢示例代碼:
```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='123456',
db='test',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
```
<br>
## 操作過程分析
**step1:連接數據庫**,操作數據庫前,我們首先需要連接數據庫,連接語句為
```python
connection = pymysql.connect(*args,**kwargs)
```
通過源碼分析,這個語句實際上是創建一個連接數據庫的`Connection類的實例`。
入參有好多,如下:

但是我們只需要記住最關鍵的幾個參數即可:
**host:** Host where the database server is located
**user:** Username to log in as
**password:** Password to use.
**database:** Database to use, None to not use a particular one.
**port:** MySQL port to use, default is usually OK. (default: 3306)
**charset:** Charset you want to use.
**step2:獲取游標**,直接執行sql語句,操作數據庫的,是一個cursor,它實際上也是一個`Cursor類的實例`,我們通過它直接與數據庫交互的,下面我們稱它為游標。
```python
cursor = connection.cursor()
```
cursor執行完sql語句后,需要記得關閉 cursor.close()
在本示例中,使用了with .. as ..上下文,就不需要再自行去關閉了。
**step3:執行sql語句**,由上一步我們自動,執行sql語句與數據庫交互的是Cursor對象,那么我們就主要需要去了解Cursor這個類有哪些方法了。
這里我們只介紹幾個最簡單的方法
* execute(self, query, args=None): 執行一個sql語句
* fetchone(self):獲取下一行匹配數據
* fetchmany(self, size=None):獲取多行匹配數據
* fetchall(self):獲取所有匹配數據
**step4:commit()提交**,所有的有關更新數據(insert,update,delete)的操作都需要commit,否則無法將數據提交到數據庫
```python
connection.commit()
```
**step5:rollback()回滾**,如果提交有異常的話,我們可以進行回滾
```python
connection.commit()
```
**step6:關閉數據庫連接**
```pyton
connection.close()
```
例如
```python
try:
# 執行sql語句
cursor.execute(sql)
# 提交執行
connection.commit()
except Exception as e:
# 如果執行sql語句出現問題,則執行回滾操作
connection.rollback()
print(e)
finally:
# 不論try中的代碼是否拋出異常,這里都會執行
# 關閉游標和數據庫連接
cursor.close()
connection.close()
```
<hr style="margin-top:100px">
:-: 
***微信掃一掃,關注“python測試開發圈”,了解更多測試教程!***
- 前言
- chapter01_開發環境
- chapter02_字符串的使用
- chapter03_列表的使用
- chapter04_字典的使用
- chapter05_數字的使用
- chapter06_元組的使用
- chapter07_集合的使用
- chapter08_輸入輸出
- chapter09_控制流程
- chapter10_實例練習_登錄1
- chapter11_python函數入門
- chapter12_python中的類
- chapter13_輕松玩轉python中的模塊管理
- chapter14_掌握學習新模塊的技巧
- chapter15_通過os模塊與操作系統交互
- chapter16_子進程相關模塊(subprocess)
- chapter17_時間相關模塊(time & datetime)
- chapter18_序列化模塊(json)
- chapter19_加密模塊(hashlib)
- chapter20_文件的讀與寫
- chapter21_階段考核2_登錄
- chapter22_小小算法挑戰(排序&二分法)
- chapter23_用多線程來搞事!
- chapter24_HTTP接口請求(requests)
- chapter25_接口測試框架(pytest)
- chapter26_階段考核3_HTTP接口測試
- chapter27_HTML解析(pyquery)
- chapter28_階段考核4_爬蟲下載網易汽車
- chapter29_python中的那些編碼坑
- chapter30_MySQL數據庫操作
- chapter31 高級特性_迭代器與生成器
- chapter32 高級特性_裝飾器
- chapter33 高級特性_列表處理