python-pymysql数据库操作

  1. 安装 pymsql
  2. 使用示例
  3. pymysql操作过程分析

安装 pymsql

pip install pymysql

使用示例

进行代码演示前,我们先在数据库中创建一个简单的表。

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对数据库的插入与查询示例代码:

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()

pymysql操作过程分析

  1. 【连接数据库】:操作数据库前,我们首先需要连接数据库,连接语句为

    connection = pymysql.connect(*args,**kwargs)
  2. 【获取游标】:直接执行sql语句,操作数据库的,是一个cursor,它实际上也是一个Cursor类的实例,我们通过它直接与数据库交互的,下面我们称它为游标。

    cursor = connection.cursor()
  3. 【执行sql语句】:由上一步我们知道,执行sql语句与数据库交互的是Cursor对象,那么我们就需要去了解Cursor这个类有哪些方法了。

    • execute(self, query, args=None): 执行一个sql语句
    • fetchone(self):获取下一行匹配数据
    • fetchmany(self, size=None):获取多行匹配数据
    • fetchall(self):获取所有匹配数据
  4. 【commit提交】:所有的有关更新数据(insert,update,delete)的操作都需要commit,否则无法将数据提交到数据库

    connection.commit()
  5. 【rollback回滚】:如果提交有异常的话,我们可以进行回滚

    connection.commit()
  6. 【关闭数据库连接】

    connection.close()

    例如:

    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交执行
        connection.commit()
    except Exception as  e:
        # 如果执行sql语句出现问题,则执行回滚操作
        connection.rollback()
        print(e)
    finally:
        # 不论try中的代码是否抛出异常,这里都会执行
        # 关闭游标和数据库连接
        cursor.close()
        connection.close()

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。
My Show My Code