欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > python如何操控mysql

python如何操控mysql

2025/2/23 21:10:01 来源:https://blog.csdn.net/a486368464/article/details/144566810  浏览:    关键词: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太麻烦了,可以在建立连接时自动提交

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词