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太麻烦了,可以在建立连接时自动提交

相关推荐
Rose sait5 分钟前
【环境配置】Linux配置虚拟环境pytorch
linux·人工智能·python
原来是好奇心12 分钟前
深入Spring Boot源码(六):Actuator端点与监控机制深度解析
java·开发语言·源码·springboot
过期动态36 分钟前
JDBC高级篇:优化、封装与事务全流程指南
android·java·开发语言·数据库·python·mysql
WizLC37 分钟前
【Java】各种IO流知识详解
java·开发语言·后端·spring·intellij idea
傻啦嘿哟1 小时前
实战:用Splash搞定JavaScript密集型网页渲染
开发语言·javascript·ecmascript
一位代码1 小时前
mysql | 常见日期函数使用及格式转换方法
数据库·mysql
Knight_AL1 小时前
Java 线程池预热(Warm-up)实战:开启与不开启到底差多少?
java·开发语言
一世琉璃白_Y1 小时前
pg配置国内数据源安装
linux·python·postgresql·centos
liwulin05061 小时前
【PYTHON】COCO数据集中的物品ID
开发语言·python
小鸡吃米…1 小时前
Python - XML 处理
xml·开发语言·python·开源