1. 为什么要和数据库进行交互?

我认为,在对产品设计开发流程中的增删改查乃至于从数据库调取数据都离不开数据库的帮助。在中小型产品的开发当中,譬如很多时候我们也可以利用后端把一些如天气,温度这种即时数据(real-time data)载入数据库中,这种时候,我们要调取也需要脚本访问数据库。

2. PyMySql库环境与安装

安装方式如下👇:

$ python3 -m pip install PyMySQL

pymsql的目前所需环境是:

Python – one of the following:

CPython >= 2.7 or >= 3.5

Latest PyPy

MySQL Server – one of the following:

MySQL >= 5.5

MariaDB >= 5.5

3. 使用示例

CRUD(增删改查)

The following examples make use of a simple table

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 ;
import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             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, ('[email protected]', '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, ('[email protected]',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

This example will print:

{'password': 'very-secret', 'id': 1}

4. 总结

这套框架是利用一个在数据库里建立cursor然后进行抓取信息。在插入数据的时候也是插入一个个tuple。