1. 程式人生 > >運維學python之爬蟲中級篇(九)Python3 MySQL 數據庫連接

運維學python之爬蟲中級篇(九)Python3 MySQL 數據庫連接

結束 學python ofo 如何 res 2.7 獲取數據 執行 mail

最近因為年底,連續兩個項目要投產上線,又趕上公司年會,忙的要死,更新有些慢,見諒。今天要說一說python如何對mysql進行操作。在 Python3.x 版本中用於連接 MySQL 服務器的庫與Python2中使用的mysqldb有所不同。本文我將為大家介紹 Python3 使用 PyMySQL庫 連接數據庫,並實現簡單的增刪改查。

1 PyMySQL介紹

PyMySql包含一個純python的MySQL客戶端庫。PyMySQL的目標是成為MySQLdb的替代品,並在CPython、PyPy和IronPython上工作。

2 版本要求

python 下列之一

  • CPython >= 2.6 or >= 3.3
  • PyPy >= 4.0
  • IronPython 2.7

mysql 下列之一

  • MySQL >= 4.1 (tested with only 5.5~)
  • MariaDB >= 5.1

我的環境版本如下:
python
技術分享圖片

Mariadb
技術分享圖片

3 安裝

直接pip方式安裝:

# pip install PyMySQL

pycharm安裝與前面類似,如下圖:
技術分享圖片

4 數據庫增刪改查

4.1 創建數據庫testdb和表users

首先要先創建一個testdb 數據庫,並且創建users表,創建語句如下:

MariaDB [(none)]> create database testdb;
Query OK, 1 row affected (0.01 sec)

MariaDB [(none)]> use testdb
# 創建users表命令
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 ;

查看創建完的表結構:

MariaDB [testdb]> describe users;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| email    | varchar(255) | NO   |     | NULL    |                |
| password | varchar(255) | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

4.2 連接數據庫

連接數據庫之前要確認以下條件是否滿足:

  • 已經創建了數據庫 testdb;
  • 在testdb數據庫中已經創建了users表;
  • 連接數據庫TESTDB使用的用戶名為 "testdb" ,密碼為 "123456",你也可以自己設定用戶名和密碼;
  • 主要如果是遠程連接阿裏雲等主機註意grant授權;
  • 已經安裝了 Python MySQLdb 模塊。

連接數據庫並獲取版本信息:

# -*- coding: utf-8 -*-
# 導入模塊
import pymysql

# 打開數據庫連接
db = pymysql.connect(‘localhost‘, ‘testdb‘, ‘123456‘, ‘testdb‘)
# 使用cursor()方法創建一個遊標對象cursor
cursor = db.cursor()
# 使用execute()方法執行SQL查詢
cursor.execute("select version()")
# 使用fetchone()獲取單條數據
data = cursor.fetchone()
# 打印獲取的內容
print(‘Vsersion: %s‘  % data)
# 關閉連接
db.close()

輸出結果如下:

Version: 10.0.33-MariaDB

4.3 數據庫插入

# -*- coding: utf-8 -*-
# 導入模塊
import pymysql

# 打開數據庫連接
db = pymysql.connect(‘localhost‘, ‘testdb‘, ‘123456‘, ‘testdb‘)
# 使用cursor()方法創建一個遊標對象cursor
cursor = db.cursor()
# sql語句
sql = "INSERT INTO users(email, password) VALUES (‘[email protected]‘, ‘123‘);"

try:
    # 執行sql語句
    cursor.execute(sql)
    # 提交到數據庫
    db.commit()
    print(‘success‘)
except:
    # 如果出錯執行回滾
    db.rollback()
    print(‘failed‘)
# 關閉數據庫連接
db.close()

執行結果:
技術分享圖片
當然上面的插入代碼也可以寫成這樣:

# -*- coding: utf-8 -*-
# 導入模塊
import pymysql

# 打開數據庫連接
db = pymysql.connect(‘localhost‘, ‘testdb‘, ‘123456‘, ‘testdb‘)
# 使用cursor()方法創建一個遊標對象cursor
cursor = db.cursor()
# sql語句
# 註意這裏是與上面不同的地方
sql = "INSERT INTO users(email, password) VALUES (%s, %s)";

try:
    # 執行sql語句
        # 註意這裏是與上面不同的地方
    cursor.execute(sql, (‘[email protected]‘, ‘456‘))
    # 提交到數據庫
    db.commit()
    print(‘success‘)
except:
    # 如果出錯執行回滾
    db.rollback()
    print(‘failed‘)
# 關閉數據庫連接
db.close()

執行結果是一樣的:
技術分享圖片

4.4 數據庫查詢

# -*- coding: utf-8 -*-
# 導入模塊
import pymysql

# 打開數據庫連接
db = pymysql.connect(‘localhost‘, ‘testdb‘, ‘123456‘, ‘testdb‘)
# 使用cursor()方法創建一個遊標對象cursor
cursor = db.cursor()
# sql語句
sql = "select * from users;"

try:
    # 執行sql語句
    cursor.execute(sql)
        # 通過fetchall獲取results對象並打印結果
    results = cursor.fetchall()
    for result in results:
        print(result)
except:
    print(‘failed‘)
# 關閉數據庫連接
db.close()

返回結果如下:

(1, ‘[email protected]‘, ‘123‘)
(2, ‘[email protected]‘, ‘456‘)

4.5 數據庫更新操作

# -*- coding: utf-8 -*-
# 導入模塊
import pymysql

# 打開數據庫連接
db = pymysql.connect(‘localhost‘, ‘testdb‘, ‘123456‘, ‘testdb‘)
# 使用cursor()方法創建一個遊標對象cursor
cursor = db.cursor()
# sql語句
sql = "update users set email = ‘[email protected]‘ where id = 1;"
sql2 = ‘select * from users;‘
try:
    # 執行sql語句
    cursor.execute(sql)
    # 提交到數據庫
    db.commit()
    cursor.execute(sql2)
    # 獲取數據結果
    results = cursor.fetchall()
    for result in results:
        print(result)
except:
    # 如果出錯執行回滾
    db.rollback()
    print(‘failed‘)
# 關閉數據庫連接
db.close()

執行結果如下:

(1, ‘[email protected]‘, ‘123‘)
(2, ‘[email protected]‘, ‘456‘)

4.6 刪除操作

# -*- coding: utf-8 -*-
# 導入模塊
import pymysql

# 打開數據庫連接
db = pymysql.connect(‘localhost‘, ‘testdb‘, ‘123456‘, ‘testdb‘)
# 使用cursor()方法創建一個遊標對象cursor
cursor = db.cursor()
# sql語句
sql = "delete from users where id = 1;"
sql2 = "select * from users;"
try:
    # 執行sql語句
    cursor.execute(sql)
    # 提交到數據庫
    db.commit()
    cursor.execute(sql2)
    results = cursor.fetchall()
    for result in results:
        print(result)
except:
    # 如果出錯執行回滾
    db.rollback()
    print(‘failed‘)
# 關閉數據庫連接
db.close()

執行結果如下:

(2, ‘[email protected]‘, ‘456‘)

5 總結

通過上面增刪改查我們已經可以看出,其實python操作mysql並不復雜,主要步驟為連接數據庫,建立遊標對象,執行sql語句,獲取結果,關閉連接。我們的重點還是要熟悉相關的sql語句,這樣才能做到遊刃有余。sql教程
中級篇就算結束了,後續會介紹高級篇框架相關知識,敬請關註。

運維學python之爬蟲中級篇(九)Python3 MySQL 數據庫連接