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和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以