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如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地