PyMySQL介绍

280 阅读1分钟

PyMySQL是一个Python MySQL客户端库,支持Python3和Python2. PyMySQL通过Python DB API操作MySQL数据库,提供了轻量级和高性能的数据访问。本篇博客将介绍PyMySQL的安装和使用,并附上增删改查的示例。

安装

在终端中输入以下命令安装PyMySQL:

pip install PyMySQL

使用

导入PyMySQL库:

import pymysql

建立数据库连接:

connection = pymysql.connect(host='localhost', user='root', password='', db='mydb')

调用execute()方法执行查询:

try:
    with connection.cursor() as cursor:
        sql = "SELECT name FROM employees WHERE salary > %s"
        cursor.execute(sql, (1000,))
        result_set = cursor.fetchall()
        for row in result_set:
            print(row[0])
finally:
    connection.close()

以上代码查询了所有薪水大于1000的员工的姓名。

增删改查示例

以下是增删改查的示例代码:

# 查询数据
with connection.cursor() as cursor:
    sql = "SELECT * FROM employees"
    cursor.execute(sql)
    result_set = cursor.fetchall()
    for row in result_set:
        print(row)

# 插入数据
with connection.cursor() as cursor:
    sql = "INSERT INTO employees (name, age, salary) VALUES (%s, %s, %s)"
    cursor.execute(sql, ('Tom', 30, 1500))
    connection.commit()

# 更新数据
with connection.cursor() as cursor:
    sql = "UPDATE employees SET salary = %s WHERE name = %s"
    cursor.execute(sql, (2000, 'Tom'))
    connection.commit()

# 删除数据
with connection.cursor() as cursor:
    sql = "DELETE FROM employees WHERE age = %s"
    cursor.execute(sql, (30,))
    connection.commit()

以上代码分别实现了查询所有员工、插入新员工、更新Tom的薪水、删除年龄为30的员工的功能。

总结

使用PyMySQL可以方便地使用Python进行MySQL数据库操作,而且PyMySQL提供了丰富的API和高性能的执行效率。上述示例代码可以帮助大家了解PyMySQL的使用方式。