python基础-pymysql

2024-08-31 22:32
文章标签 python 基础 pymysql

本文主要是介绍python基础-pymysql,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

      • 安装模块
      • 基础用法
      • %占位符封装sql语句
      • 传递参数形式
      • 增、删、改
        • 增加数据库数据
        • 删除数据库数据
        • 修改数据库数据
        • 查询
      • 批量操作
      • 获取插入的数据id
      • 链接池
      • 加锁

安装模块

pip install pymysql

或者如下的方式
这里写图片描述

基础用法

创建数据库如下:

CREATE TABLE `test` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` char(10) NOT NULL,`age` int(11) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

表如下:
这里写图片描述


import pymysql
# 获取用户输入
# name = input("用户名>>:")
# pwd = input("密码>>:")# 校验用户输入的用户名和密码是否正确
# 去数据库里取数据做判断
# 1. 连上数据库
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8")  # 不是utf-8
# 光有链接还不行,需要获取光标,让我能够输入SQL语句并执行
cursor = conn.cursor()
# 2. 执行SQL语句 --> select * from userinfo where name=name and pwd=pwd
sql = "select * from test WHERE id > 3;"
ret = cursor.execute(sql)
# 关闭光标和连接
cursor.close()
conn.close()print("%s row in set (0.00 sec)" % ret)

输出结果如下:

4 row in set (0.00 sec)

%占位符封装sql语句

import pymysql
# 获取用户输入name = input("用户名>>:")
pwd = input("密码>>:")# 校验用户输入的用户名和密码是否正确
# 去数据库里取数据做判断
# 1. 连上数据库
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8")  # 不是utf-8
# 光有链接还不行,需要获取光标,让我能够输入SQL语句并执行
cursor = conn.cursor()
# 2. 执行SQL语句 --> select * from userinfo where name=name and pwd=pwd
sql = "select * from test WHERE name='%s' and age=%s;" % (name, pwd)
print(sql)
ret = cursor.execute(sql)  # 获取影响的行数
# 关闭光标和连接
cursor.close()
conn.close()
if ret:print("登陆成功")
else:print("登录失败")

运行结果如下:

用户名>>:xiao
密码>>:11
select * from test WHERE name='xiao' and age=11;
登陆成功

传递参数形式

import pymysql
# 获取用户输入
name = input("用户名>>:")
pwd = input("密码>>:")# 校验用户输入的用户名和密码是否正确
# 去数据库里取数据做判断
# 1. 连上数据库
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8")  # 不是utf-8
# 光有链接还不行,需要获取光标,让我能够输入SQL语句并执行
cursor = conn.cursor()
# 2. 执行SQL语句 --> select * from userinfo where name=name and pwd=pwd
sql = "select * from test WHERE name=%s and age=%s;"
print(sql)
# 让pymysql拼接字符串
ret = cursor.execute(sql, [name, pwd])  # 获取影响的行数
# 关闭光标和连接
cursor.close()
conn.close()
if ret:print("登陆成功")
else:print("登录失败")

输出如下:

用户名>>:xiao
密码>>:11
select * from test WHERE name=%s and age=%s;
登陆成功

注意的是:
sql = “select * from test WHERE name=%s and age=%s;”
如果改成如下:

sql = "select * from test WHERE name='%s' and age=%s;"

报错如下:
这里写图片描述

或者如下的方式:

import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='test')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# cursor.execute("select id,name from users where name=%s and pwd=%s",['safly','123',])
cursor.execute("select id,user from user where user =%(user)s and pwd=%(pwd)s",{'user':'alex','pwd':'123'})
obj = cursor.fetchone()
conn.commit()
cursor.close()
conn.close()print(obj)

输出如下:
{‘id’: 1, ‘user’: ‘safly’}

增、删、改

增加数据库数据
import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8")  # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "insert into test(name, age) VALUE (%s, %s);"username = "Egon2"
#以下2种均可
password = "324"
password = 324
try:# //insert into 表名 (列名1,列名2,列名3) values (值1,值2,值3),(值1,值2,值3)# 执行SQL语句cursor.execute(sql, (username, password))conn.commit()  # 把修改提交到数据库
except Exception as e:conn.rollback()cursor.close()
conn.close()
删除数据库数据
import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8")  # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "delete from test where name=%s"
username = "Egon2"
try:# 执行SQL语句cursor.execute(sql, (username,))conn.commit()  # 把修改提交到数据库
except Exception as e:conn.rollback()cursor.close()
conn.close()
修改数据库数据
import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8")  # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "update test set age=%s where name=%s"print(sql)
username = "xiao"
age = 11111111
try:# 执行SQL语句cursor.execute(sql, (age, username))conn.commit()  # 把修改提交到数据库
except Exception as e:conn.rollback()cursor.close()
conn.close()
查询

目前数据库数据如下:
这里写图片描述

import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8")  # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "select * from test;"# 执行SQL语句
ret = cursor.execute(sql)
print("-->",ret)
# 一次取一条
print(cursor.fetchone())
print(cursor.fetchone())
print(cursor.fetchmany(3))# 一次取所有
print(cursor.fetchall())
# 一起取三条# 进阶用法# # 移动取数据的光标
cursor.scroll(-2)  # 默认是相对移动
print(cursor.fetchone())
# # 按照绝对位置去移动
cursor.scroll(4, mode="absolute")
print(cursor.fetchone())
cursor.close()
conn.close()

输出如下:

--> 9
(1, '小李', 1)
(2, '小王', 2)
((4, 'xsiao', 11), (5, 'xffdfdiao', 11), (13, 'Egon2', 324))
((14, 'wyf', 324), (15, 'aaa', 324), (16, 'ewtr', 324), (17, 'ewtr', 324))
(16, 'ewtr', 324)
(13, 'Egon2', 324)

批量操作

批量插入数据库数据

import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8")  # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "insert into test (name, age) VALUES (%s, %s);"
user1 = "wyf1"
pwd1 = 11
user2 = "wyf2"
pwd2 = 22data = ((user1, pwd1), (user2, pwd2))try:# 执行SQL语句# cursor.execute(sql, (user1, pwd1))# cursor.execute(sql, (user2, pwd2))cursor.executemany(sql, data)conn.commit()  # 把修改提交到数据库
except Exception as e:conn.rollback()cursor.close()
conn.close()

获取插入的数据id

import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8")  # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "insert into test (name, age) VALUES (%s, %s);"
user1 = "Egon3"
pwd1 = 234try:# 执行SQL语句cursor.execute(sql, (user1, pwd1))conn.commit()  # 把修改提交到数据库# 拿到我插入这条数据的IDlast_id = cursor.lastrowidprint("--> 刚才插入的那条数据的ID值是:", last_id)
except Exception as e:conn.rollback()cursor.close()
conn.close()

输出如下:

--> 刚才插入的那条数据的ID值是: 22

链接池

import time
import pymysql
import threading
from DBUtils.PooledDB import PooledDB, SharedDBConnection
POOL = PooledDB(creator=pymysql,  # 使用链接数据库的模块maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建maxcached=5,  # 链接池中最多闲置的链接,0和None不限制maxshared=3,  # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]ping=0, # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = alwayshost='127.0.0.1',port=3306,user='root',password='root',database='test',charset='utf8'
)def func():conn = POOL.connection()cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)cursor.execute('select * from user ')result = cursor.fetchall()cursor.close()conn.close()return resultret = func()
print(ret)

输出[{'user': 'alex', 'pwd': '123', 'id': 1}]

加锁

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
import threading
from threading import RLockLOCK = RLock()
CONN = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='root',database='test',charset='utf8')def task(arg):with LOCK:cursor = CONN.cursor()cursor.execute('select * from user ')result = cursor.fetchall()cursor.close()print(result)for i in range(10):t = threading.Thread(target=task, args=(i,))t.start()
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)

这篇关于python基础-pymysql的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1125174

相关文章

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v