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

相关推荐
养猫的程序猿1 分钟前
Libvio.link爬虫技术解析大纲
python
野犬寒鸦1 小时前
从零起步学习并发编程 || 第四章:synchronized底层源码级讲解及项目实战应用案例
java·服务器·开发语言·jvm·后端·学习·面试
£漫步 云端彡1 小时前
Golang学习历程【第十一篇 接口(interface)】
开发语言·学习·golang
a1117768 小时前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
液态不合群9 小时前
[特殊字符] MySQL 覆盖索引详解
数据库·mysql
0思必得09 小时前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
virus59459 小时前
悟空CRM mybatis-3.5.3-mapper.dtd错误解决方案
java·开发语言·mybatis
初次见面我叫泰隆9 小时前
Qt——3、常用控件
开发语言·qt·客户端
无小道10 小时前
Qt——QWidget
开发语言·qt
时艰.10 小时前
Java 并发编程之 CAS 与 Atomic 原子操作类
java·开发语言