pymysql 库 - python 操作 mysql

news/2025/3/28 16:52:35/

环境: Win10 x64 + Python 3.7 + PyMySQL  1.0.2 + MySQL 8.0.27

1 安装

pip install pymysql

2 地址

https://pypi.org/project/pymysql/

3.1 数据库版本查询 (search_version.py)


import pymysql# 打开数据库连接
try:db = pymysql.connect(host='localhost', user='root', passwd='123456', port=3306)print('连接成功!')
except:print('something wrong!')# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()# 使用 execute()  方法执行 SQL 查询
cursor.execute("SELECT VERSION()")# 使用 fetchone() 方法获取单条数据.fetchone只返回一维元组
data = cursor.fetchone()
print(type(data))
print(data)
print("Database version : %s " % data)# 关闭数据库连接
db.close()'''
连接成功!
<class 'tuple'>
('8.0.27',)
Database version : 8.0.27 
'''

3.2 创建表 (create_table.py)


import pymysql# 打开数据库连接
try:db = pymysql.connect(host='localhost', user='root', passwd='123456', port=3306, db='db_jupiter')print('连接成功!')
except:print('something wrong!')# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")# 使用预处理语句创建表
sql = """CREATE TABLE EMPLOYEE (ID INT NOT NULL AUTO_INCREMENT,FIRST_NAME  CHAR(20) NOT NULL COMMENT '名字',LAST_NAME  CHAR(20),AGE INT COMMENT '年龄',  SEX CHAR(1) COMMENT '性别',INCOME FLOAT NOT NULL COMMENT '收入',PRIMARY KEY (ID))"""cursor.execute(sql)
print('建表成功!')# 关闭数据库连接
db.close()'''
连接成功!
建表成功!
'''

3.3 插入数据 (insert_update_delete_table.py)


import pymysql# 打开数据库连接
try:db = pymysql.connect(host='localhost', user='root', passwd='123456', port=3306, db='db_jupiter')print('连接成功!')
except:print('something wrong!')# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()# SQL 插入语句
# sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES ('Qin', 'DeXu', 20, 'M', 2000)"""
# sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES ('Li', 'Xiaofei', 20, 'F', 3000)"""
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES ('Wang', 'HanYu', 20, 'M', 5000)"""# SQL 更新语句
# sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')# SQL 删除语句
# sql = "DELETE FROM EMPLOYEE WHERE AGE > %d" % (20)try:# 执行sql语句cursor.execute(sql)# 提交到数据库执行db.commit()print('数据插入成功!')
except:# 如果发生错误则回滚db.rollback()print('数据插入错误!')# 关闭数据库连接
db.close()'''
连接成功!
数据插入成功!
'''

3.4 批量插入数据 (insert_table_many.py)


import pymysql# 打开数据库连接
try:db = pymysql.connect(host='localhost', user='root', passwd='123456', port=3306, db='db_jupiter')print('连接成功!')
except:print('something wrong!')# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()# SQL 插入语句
data = [('DongFang', 'YuXiao', 25, 'M', 2000.30),('OuYang', 'HeHe', 22, 'F', 2000),('GongSun', 'Sheng', 23, 'M', 2000)
]stmt = "INSERT INTO EMPLOYEE (FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES (%s, %s, %s, %s, %s)"try:# 执行sql语句cursor.executemany(stmt, data)# 提交到数据库执行db.commit()print('数据插入成功!')
except:# 如果发生错误则回滚db.rollback()print('数据插入错误!')# 关闭数据库连接
db.close()'''
连接成功!
数据插入成功!
''''''
说明:
占位符 %s 改成 %d ,报错。
'''

3.5 查询数据 (search_table.py)


import pymysql# 打开数据库连接
try:db = pymysql.connect(host='localhost', user='root', passwd='123456', port=3306, db='db_jupiter')print('连接成功!')
except:print('something wrong!')# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE WHERE INCOME >= %s" % (3000)try:# 执行SQL语句cursor.execute(sql)# rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。row_count = cursor.rowcountprint(type(row_count))print(row_count)# fetchall(): 接收全部的返回结果行, 获取所有记录列表 fetchall返回二维元组(元组中含有元组)results = cursor.fetchall()print(type(results))print(results)for row in results:id = row[0]fname = row[1]lname = row[2]age = row[3]sex = row[4]income = row[5]# 打印结果print('数据查询成功!')print("id=%s, fname=%s, lname=%s, age=%s, sex=%s, income=%s" % (id, fname, lname, age, sex, income))
except:print("Error: unable to fetch data")# 关闭数据库连接
db.close()'''
连接成功!
<class 'int'>
2
<class 'tuple'>
((2, 'Li', 'Xiaofei', 20, 'F', 3000.0), (3, 'Wang', 'HanYu', 20, 'M', 5000.0))
数据查询成功!
id=2, fname=Li, lname=Xiaofei, age=20, sex=F, income=3000.0
数据查询成功!
id=3, fname=Wang, lname=HanYu, age=20, sex=M, income=5000.0
'''

其他情况:
executemany()方法要求传入的参数是元组嵌套的列表,列表中每个元组代表一组数据,而元组中的每个值则代表一个数据的字段值。

####################################
批量插入1:
data = [
  ('Jane', date(2005, 2, 12)),
  ('Joe', date(2006, 5, 23)),
  ('John', date(2010, 10, 3)),
]

stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)

INSERT INTO employees (first_name, hire_date)
VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')

####################################
批量插入2:
# 定义 SQL 语句
insert_sql = "INSERT INTO person VALUES (%s, %s, %s)"

# 定义数据
data = [
    ('1', '张三', 18),
    ('2', '李四', 19),
    ('3', '王五', 20)
]
# 批量插入数据
cursor.executemany(insert_sql, data)

批量删除3:
# 定义 SQL 语句
delete_sql = "DELETE FROM  WHERE id = %s"
# 定义数据
ids = [(1,), (2,), (3,)]
# 批量删除数据
cursor.executemany(delete_sql, ids)


参考链接:
https://zhuanlan.zhihu.com/p/397765212
http://www.xoxxoo.com/index/index/article/id/288
https://blog.csdn.net/m0_48300767/article/details/131063781
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html


http://www.ppmy.cn/news/1020600.html

相关文章

Hello,SpringBoot!

一、回顾什么是Spring Spring是一个开源框架&#xff0c;2003 年兴起的一个轻量级的Java 开发框架&#xff0c;作者&#xff1a;Rod Johnson Spring是为了解决企业级应用开发的复杂性而创建的&#xff0c;简化开发。 Spring是如何简化Java开发的 为了降低Java开发的复杂性…

JVM 垃圾回收

垃圾回收算法 标记-清除算法&#xff08;Mark and Sweep&#xff09; 标记-清除算法分为两个阶段。在标记阶段&#xff0c;垃圾收集器会标记所有活动对象&#xff1b;在清除阶段&#xff0c;垃圾收集器会清除所有未标记的对象。标记-清除算法存在的问题是会产生内存碎片&#…

【YOLOX】《YOLOX:Exceeding YOLO Series in 2021》

arXiv-2021 文章目录 1 Background and Motivation2 Related Work3 Advantages / Contributions4 Method5 Experiments5.1 Datasets and Metrics 6 Conclusion&#xff08;own&#xff09; 1 Background and Motivation 2 Related Work 3 Advantages / Contributions 4 Meth…

【BASH】回顾与知识点梳理(二十)

【BASH】回顾与知识点梳理 二十 二十. 十六至十九章知识点总结及练习20.1 总结20.2 练习 该系列目录 --> 【BASH】回顾与知识点梳理&#xff08;目录&#xff09; 二十. 十六至十九章知识点总结及练习 20.1 总结 shell script 是利用 shell 的功能所写的一个『程序 (prog…

年之年的选择,组装版

组件&#xff1a;<!--* Author: liuyu liuyuxizhengtech.com* Date: 2023-02-01 16:57:27* LastEditors: wangping wangpingxizhengtech.com* LastEditTime: 2023-06-30 17:25:14* Description: 时间选择年 - 年 --> <template><div class"year-range-pick…

列队 Queue 接口概述

在Java中&#xff0c;Queue&#xff08;队列&#xff09;是一种基本的数据结构&#xff0c;用于按照先进先出&#xff08;FIFO&#xff09;的顺序存储元素。Java提供了多种实现Queue接口的类&#xff0c;以下是几种常见的实现方式&#xff1a; LinkedList&#xff1a;LinkedLis…

【算法训练营】队列 合集(1)

&#x1f4cd;前言 本篇将学习queue的OJ题并学习queue的基础知识。 &#x1f57a;作者&#xff1a; 主页 我的专栏C语言从0到1探秘C数据结构从0到1探秘Linux菜鸟刷题集 &#x1f618;欢迎关注&#xff1a;&#x1f44d;点赞&#x1f64c;收藏✍️留言 &#x1f3c7;码字不易&a…

有答案:10个网络工程师面试常见问题

目录 1、交换机转发数据包的原理&#xff1f; 2. 数据包如果经过二层交换机转发后&#xff0c;那这个数据包的源MAC会变化吗&#xff1f;如果经过三层交换机理由转发&#xff0c;那源MAC会变成什么呢&#xff1f; 3. 如何查看PC的ARP表&#xff0c;如何清除ARP表&#xff0c…