python常识系列24-->python操作mysql之pymysql

前言

  1. pymsql是Python中操作MySQL的模块
  2. 程序在运行时,数据都是在内存中的。当程序终止时,通常需要将数据保存在磁盘上。

安装模块

python 复制代码
pip install PyMySql

基本使用

python 复制代码
## 使用 connect 函数创建连接对象,此连接对象提供关闭数据库、事务回滚等操作。
connect = pymysql.connect(host='127.0.0.1',
                     user='root',
                     password='pwd',
                     database='database_name')
# 获取游标
start = connect.cursor()
#默认获取数据的格式为元组格式

cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
#设置cursor设置为pymysql.cursors.DictCursor,可以将显示数据为 字典格式

cursor.scroll(1,mode='relative')  # 相对当前位置移动
cursor.scroll(2,mode='absolute') # 相对绝对位置移动
# 第一个值为移动的行数,整数为向下移动,负数为向上移动,mode指定了是相对当前位置移动,还是相对于首行移动

# 执行sql语句
start.execute()
    # 执行单条语句
start.executemany()
    # 执行多条语句

#获取单条数据
dp = start.fetchone()

# 获取所有数据
dp = start.fetchall()

# 获取指定条数数据
dp = start.fetchone(3)
    #获取3条数据

# 关闭数据库连接
db.close()

具体实例之查询select

python 复制代码
import pymysql

# 创建数据库连接对象
connect = pymysql.connect(host='127.0.0.1',
                          user='root',
                          password='pwd',
                          database='database_name')
# 创建游标对象
cursor = connect.cursor()

table_name = 'school_info_table'
sql = "SELECT * FROM %s WHERE schoolname LIKE '%深圳%' " % table_name
try:
    cursor.execute(sql)  # 执行sql语句,也可执行数据库命令,如:show tables
    result = cursor.fetchall()  # 所有结果
    print(result)
except Exception as e:
    connect.rollback()
    print("select Fail")
    print(e)
finally:
    cursor.close()  # 关闭当前游标
    connect.close()  # 关闭数据库连接

具体实例之修改update

python 复制代码
import pymysql

# 创建数据库连接对象
connect = pymysql.connect(host='127.0.0.1',
                          user='root',
                          password='pwd',
                          database='database_name')
# 创建游标对象
cursor = connect.cursor()

table_name = 'table_name '
user_id = 'yyy'
user_no = 'xxx'
sql = "UPDATE %s SET user_no = '%s' WHERE user_id = '%s'" % (table_name, user_no, user_id)
try:
    cursor.execute(sql)  # 执行sql语句,也可执行数据库命令,如:show tables
    connect.commit()  # 增删改,必须执行事务
    print("update success")
except Exception as e:
    connect.rollback()  # 若出现失败,进行回滚
    print("update fail")
    print(e)
finally:
    cursor.close()  # 关闭当前游标
    connect.close()  # 关闭数据库连接
相关推荐
qinzechen1 分钟前
分享几个做题网站------学习网------工具网;
java·c语言·c++·python·c#
hakesashou2 分钟前
python交互式命令时如何清除
java·前端·python
不写八个16 分钟前
Python办公自动化教程(005):Word添加段落
开发语言·python·word
火红的小辣椒22 分钟前
XSS基础
android·web安全
_.Switch34 分钟前
Python机器学习框架介绍和入门案例:Scikit-learn、TensorFlow与Keras、PyTorch
python·机器学习·架构·tensorflow·keras·scikit-learn
赵荏苒1 小时前
Python小白之Pandas1
开发语言·python
计算机学姐1 小时前
基于SpringBoot+Vue的高校运动会管理系统
java·vue.js·spring boot·后端·mysql·intellij-idea·mybatis
-XWB-1 小时前
【MySQL】数据目录迁移
数据库·mysql
一眼万里*e1 小时前
fish-speech语音大模型本地部署
python·flask·大模型
结衣结衣.2 小时前
python中的函数介绍
java·c语言·开发语言·前端·笔记·python·学习