本文共 4586 字,大约阅读时间需要 15 分钟。
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,安装方便且支持 Python3。它提供了基本的数据库操作功能,适合用于简单的爬虫、自动化任务或小型项目。以下将详细介绍如何使用 PyMySQL 连接 MySQL 数据库并实现增删改查操作。
在安装 PyMySQL 之前,确保已安装 Python3环境。安装步骤如下:
pip list
pip install pymysql
cryptography 包进行加密,确保其安装:pip install cryptography
在使用 PyMySQL 前,需要创建一个 py_db 数据库。以下是连接数据库的代码示例:
import pymysql# 获取数据库连接dbConn = pymysql.connect( host='localhost', port=3306, user='root', password='***', database='py_db', cursorclass=pymysql.cursors.DictCursor)# 创建游标对象cursor = dbConn.cursor()# 查询结果print(cursor)
游标是数据库操作的核心工具,用于执行增删改查操作。操作完成后,务必释放游标和数据库连接:
cursor = dbConn.cursor()
cursor.close()
使用 execute() 方法执行 SQL 语句创建表:
create_table_sql = """ CREATE TABLE `t_user` ( `id` bigint NOT NULL AUTO_INCREMENT, `user_name` varchar(145) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, `sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, `age` int DEFAULT NULL, `birthday` date DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB"""
执行创建表操作:
res = cursor.execute(create_table_sql)print(res) # 0cursor.close()dbConn.close()
PyMySQL 提供了多种方法执行插入操作,包括 execute()、executemany() 和参数化查询。
insert_sql = """ INSERT INTO `t_user` ( `user_name`, `password`, `sex`, `age`, `birthday` ) VALUES (%s, %s, %s, %s, %s)"""try: insert_data = ("赵云", "123456", "男", 20, "2023-02-13") res = cursor.execute(insert_sql, insert_data) print(res) # 1 dbConn.commit()except: dbConn.rollback()finally: cursor.close() dbConn.close() import timeinsert_sql = """ INSERT INTO `t_user` ( `user_name`, `password`, `sex`, `age`, `birthday` ) VALUES (%s, %s, %s, %s, %s)"""try: insert_data = ("赵云2", "123456", "男", 18, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) res = cursor.execute(insert_sql, insert_data) print(res) # 1 dbConn.commit()except: dbConn.rollback()finally: cursor.close() dbConn.close() import timeinsert_sql = """ INSERT INTO `t_user` ( `user_name`, `password`, `sex`, `age`, `birthday` ) VALUES (%s, %s, %s, %s, %s)"""insert_datas = [ ("赵子龙1", "123456", "男", 18, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())), ("赵子龙2", "123456", "男", 19, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())), ("赵子龙3", "123456", "男", 20, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))]try: res = cursor.executemany(insert_sql, insert_datas) print(res) # 3 dbConn.commit()except: dbConn.rollback()finally: cursor.close() dbConn.close() update_sql = """ UPDATE `t_user` SET `user_name` = %s, `password` = %s, `sex` = %s, `age` = %s WHERE `id` = %s"""update_data = ("安琪拉", "123456", "女", 18, 2)try: res = cursor.execute(update_sql, update_data) print(res) # 1 dbConn.commit()except: dbConn.rollback()finally: cursor.close() dbConn.close() delete_sql = """ DELETE FROM `t_user` WHERE `id` = %s"""delete_datas = [1, 2]try: res = cursor.executemany(delete_sql, delete_datas) print(res) # 2 dbConn.commit()except: dbConn.rollback()finally: cursor.close() dbConn.close()
PyMySQL 提供了多种查询方法,如 fetchone()、fetchall() 和 fetchmany()。
select_sql = """ SELECT * FROM `t_user` WHERE id = %s"""select_data = (5)try: cursor.execute(select_sql, select_data) res = cursor.fetchone() print(res) # {'id': 5, 'user_name': '赵子龙1', 'password': '123456', 'sex': '男', 'age': 18, 'birthday': '2023-02-13'}except: raisefinally: cursor.close() dbConn.close() select_sql = """ SELECT * FROM `t_user` WHERE id >= %s AND sex = %s"""select_data = (5, "男")try: cursor.execute(select_sql, select_data) res = cursor.fetchmany(5) for row in res: print(row) print(f"id={row['id']}, username={row['user_name']}, password={row['password']}, sex={row['sex']}, age={row['age']}, birthday={row['birthday']}")except: raisefinally: cursor.close() dbConn.close() PyMySQL 支持事务操作,事务具有原子性、一致性、隔离性和持久性。默认情况下,数据库操作会隐式开始一个事务,操作完成后需显式提交或回滚。
dbConn.commit()
dbConn.rollback()
PyMySQL 是一个功能强大的库,适合用于连接和操作 MySQL 数据库。通过掌握以上操作,开发者可以轻松实现数据库的增删改查操作,并通过事务机制确保数据的完整性。
转载地址:http://ivofk.baihongyu.com/