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

相关推荐
chilavert3184 小时前
技术演进中的开发沉思-356:重排序(中)
java·开发语言
jianghua0014 小时前
Python中的简单爬虫
爬虫·python·信息可视化
czlczl200209254 小时前
增删改查时如何提高Mysql与Redis的一致性
数据库·redis·mysql
打工的小王4 小时前
MySql(二)索引
数据库·mysql
devmoon4 小时前
为 Pallet 搭建最小化 Mock Runtime 并编写单元测试环境
开发语言·单元测试·区块链·智能合约·polkadot
喵手4 小时前
Python爬虫实战:针对Python官网,精准提取出每一个历史版本的版本号、发布日期以及对应的文档/详情页链接等信息,并最终清洗为标准化的CSV文件!
爬虫·python·爬虫实战·零基础python爬虫教学·python官方数据采集·采集历史版本版本号等信息·导出csv文件
Coder_Boy_4 小时前
Java开发者破局指南:跳出内卷,借AI赋能,搭建系统化知识体系
java·开发语言·人工智能·spring boot·后端·spring
databook4 小时前
像搭积木一样思考:数据科学中的“自下而上”之道
python·数据挖掘·数据分析
Mr_Xuhhh4 小时前
介绍一下ref
开发语言·c++·算法
luoluoal4 小时前
基于python的医疗问句中的实体识别算法的研究(源码+文档)
python·mysql·django·毕业设计·源码