首页 > 数据库 >Python 操作pymysql模块

Python 操作pymysql模块

时间:2022-11-28 23:23:28浏览次数:43  
标签:Python pymysql cursor 获取 模块 操作 conn

内容概要

  • pymysql模块安装
  • python 操作 pymysql模块
  • 补充说明

pymysql 安装

我们可以在pycharm 直接 import pymsql ,然后点击上面的小灯泡 点击 install即可
或者在cmd中输入指令
	pip install pymysql

python操作 pymysql模块

import pymysql

# 1.连接pymysql服务端
conn = pymysql.connect(
    host='127.0.0.1',  # IP地址
    user='root',  # 用户名
    password='suiyuan521', # 密码
    port=3306, # mysql端口号
    db='db4', # 需要操作的数据库
    charset='utf8mb4'  # 字符编码设置
    autocommit=True  # 确认增删改查
)
# cursor = conn.cursor() # 括号内不填写额外参数数据是元组 指定性不强[(),()]
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql1 = 'select * from teacher;'
affect_rows = cursor.execute(sql1)  # execute 也有返回值,返回的是SQL语句影响的行数
res = cursor.fetchall()  # 获取SQL语句执行之后的结果
print(res)

1.获取数据
fetchall() 获取所有的结果
fetchone() 获取结果集的第一个数据
fetchmany() 获取指定数量的结果集
ps:注意三者都有类似于文件光标移动的特性

cursor.scroll(1,'relative')  # 基于当前位置往后移动
cursor.scroll(0,'absolute')  # 基于数据的开头往后移动

2.增删改查
autocommit=True # 针对增 删 改 自动确认(直接配置)
conn.commit() # 针对 增 删 改 需要二次确认(代码确认)

标签:Python,pymysql,cursor,获取,模块,操作,conn
From: https://www.cnblogs.com/ddsuifeng/p/16934110.html

相关文章