我的账户
码尚云教育

云计算企业项目实战营

亲爱的游客,欢迎!

已有账号,请

如尚未注册?

python怎么连接mysql数据库?

[复制链接]
云鼎 发表于 2022-9-19 14:24:42 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
使用环境:Windows+python3.7+MySQL5.5+Navicat
1.准备工作安装:
  pip install MySQLClient
2.使用mysql使用流程
   开始->创建connection->获取cursor->执行查询/执行命令/获取数据/处理数据->关闭cursor->关闭connection->结束
3.创建方法导入(简单的mysql数据库建立连接就完成了,接下来就可以写对数据增删改查操作)
  • import MySQLdb
  • conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='root1234',db='test_auto_new',charset='utf8')
  • #创建并且返回游标
  • cursor=conn.cursor()
  • #查询表
  • cursor.execute("select * from auth_user");
  • results=cursor.fetchall()
  • for row in results:
  •     name=row
  •     print(name)
  •     #删除表
  •     id=6
  •     sql="delete from auth_user where id='%s'" %(id)
  •     try:
  •         #用于执行一个数据库的查询命令
  •         cursor.execute(sql);
  •         #提交
  •         conn.commit();
  •     except:
  •         #回滚当前事物
  •         conn.rollback();

[color=rgb(15, 199, 122) !important]复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

maxs
  • 管理员
此人很懒,什么都没有留下。

关注0

粉丝0

帖子45

发布主题
大家都在学
课堂讨论
关注我们
码尚云云计算培训

客服电话:18710061913

周一至周日: 7:00-24:00

码尚云教育( 陕ICP备2023009934号-2 )

Powered by Discuz! X3.4© 2016-2023 Comsenz Inc.