python如何操控mysql

1、在anaconda中新创建pymysql环境

conda create -n pymysql python=3.12

2、安装pymysql第三方库

成功

3、创建learn_pymysql项目

4、编写代码连接本地数据库

代码

from pymysql import Connection

conn=Connection(

host='localhost',

port=3306,

user='root',

password='zzlb486591...'

)

print(conn.get_server_info())

conn.close()

运行报错

raise RuntimeError(

RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods

搜索说是需要 pip install cryptography

再次运行

5、编写代码执行DDL

代码

# get cursor

cursor=conn.cursor()

# select db

conn.select_db("test_transaction")

# execute sql

cursor.execute("create table test(id int,info varchar(255));")

成功

不写分号也没问题

6、编写代码

代码

# execute query_sql

cursor.execute("select * from account")

results:tuple=cursor.fetchall()

for r in results:

print(r)

运行结果

和数据库一样

7、编写代码插入数据

代码

# execute insert_sql

cursor.execute("insert into test values(1,'a')")

conn.commit()

运行结果

每次都需要commit太麻烦了,可以在建立连接时自动提交

相关推荐
2601_966949652 分钟前
批量 K 线不只是提速:因子研究中的数据质量、复权与回测偏差
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
matlab代码3 分钟前
基于matlab水果识别系统(西红柿、香蕉、梨、青椒)【源码64期】
开发语言·matlab
一位正在转型AI全栈的前端工程师3 分钟前
AI 全栈学习之旅 -Week 11:从 CLI 到浏览器:用 FastAPI、SSE 和 Vue 3 做一个可审核的 ReAct Agent
前端·python
王的宝库6 分钟前
Gin + GORM
开发语言·golang·gin
零基础的修炼9 分钟前
CUDA知识汇总
开发语言·c++·编辑器
洛阳纸贵9 分钟前
AI-PyTorch(一)基础代码实操和自动求导
人工智能·pytorch·python
妙码生花12 分钟前
golang 应用服务端部署(使用 systemd 服务)
开发语言·人工智能·后端·golang·node.js·php·gin
2601_9622845017 分钟前
uv:终结 Python 虚拟环境管理乱局
python·项目管理·uv·虚拟环境·依赖管理
重生之小比特17 分钟前
【Java SE】运算符
java·开发语言
Patrick在香港26 分钟前
Claude + Python 数据管道:一次字段改名,786 行历史数据被静默重写
开发语言·windows·python·claude·数据工程·数据校验·数据管道