python3连接MySQL8.0的两种方式

作者:兔猪合家欢 时间:2024-01-20 20:16:14 

1、下载MySQL官方的mysql-connector-python-8.0.17-py3.7-windows-x86-64bit.msi,直接点击安装;

2、安装完毕后直接可以导入mysql.connnector模块

连接方式一:


import mysql.connector
cnx = mysql.connector.connect(user='scott', password='password', host='127.0.0.1', database='employees')
cnx.close()

连接方式二:


from mysql.connector import (connection)
cnx = connection.MySQLConnection(user='scott', password='password', host='127.0.0.1', database='employees')
cnx.close()

用try~except获取错误代码:


import mysql.connector
from mysql.connector import errorcode
try:
cnx = mysql.connector.connect(user='scott', database='employ')
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()

3、获取数据库数据:


import mysql.connector
myconn=mysql.connector.connect(host="localhost",user="lucy",passwd="123455",database="holiday")
mycursor=myconn.cursor()
my_cmd_sql="select * from birthday"
a=mycursor.execute(my_cmd_sql) #执行SQL命令
for a in mycursor:    #展示请求数据
 print(a)
mycursor.close()     #指针必须关闭
myconn.close()      #连接必须关闭

4、插入、更改和删除数据

跟上面一样的方法执行插入、更改和数据命令,这里有一点区别,execute语句后必须调用连接的.commit()方法确认执行。

另外:指针一定要关闭,否则容易引起

mysql 2014 error (2014) Commands out of sync; You can't run this command now

总结

以上所述是小编给大家介绍的python3连接MySQL8.0的两种方式网站的支持!

来源:https://blog.csdn.net/m0_46301035/article/details/104349326

标签:python3,连接,MySQL8.0
0
投稿

猜你喜欢

  • Python telnet登陆功能实现代码

    2022-08-13 01:52:56
  • Python 利用base64库 解码本地txt文本字符串

    2021-01-13 14:33:58
  • 使用IronPython把Python脚本集成到.NET程序中的教程

    2023-08-05 04:52:14
  • python交换两个变量的值方法

    2022-07-28 10:10:48
  • 对python中的xlsxwriter库简单分析

    2022-08-22 22:46:01
  • Python实现二维有序数组查找的方法

    2021-04-15 21:31:38
  • 浅谈python中列表、字符串、字典的常用操作

    2023-02-02 23:59:15
  • Javascript模拟加速运动与减速运动代码分享

    2024-06-07 15:27:46
  • pandas string转dataframe的方法

    2021-08-15 14:47:04
  • python实现微信自动回复机器人功能

    2023-12-30 01:01:40
  • Python爬虫框架Scrapy常用命令总结

    2022-02-21 20:45:23
  • Yii入门教程之Yii安装及hello world

    2024-06-05 15:39:45
  • 一个简单的北京2008奥运倒计时代码

    2008-03-16 14:15:00
  • tensorflow: 查看 tensor详细数值方法

    2022-07-24 09:40:37
  • 深入理解JavaScript作用域和作用域链

    2024-04-10 13:54:17
  • python修改微信和支付宝步数的示例代码

    2021-08-31 08:45:06
  • Numpy数组array和矩阵matrix转换方法

    2021-06-25 06:17:26
  • 学习Python,你还不知道main函数吗

    2022-11-02 10:20:43
  • python matplotlib如何给图中的点加标签

    2023-02-23 12:16:47
  • 详解git合并冲突解决方法

    2023-05-11 05:18:34
  • asp之家 网络编程 m.aspxhome.com