前提
文章针对的是mysql8.0以上版本,使用navicat连接数据库
问题
MySQL8.0级以上版本支持"caching_sha2_password"的加密方式,而不支持"mysql_native_password",是网上一些代码无法运行
导入mysql-connector
手动导入
1.选择“File”在选择“settings”
2.进入“Settings”界面后,选择“Project:PythonProject”,如下
3.点击“+”号
4.搜索“mysql-connector”,选择包,点击左下角“Install Package”
navicat操作
1.新建一个查询
2.输入sql代码,修改为相应的
# 'username'用户名,'password'密码
ALTER USER 'username'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
连接数据库以增加数据库为例
# 加载包,运行没有问题即mysql.connector已经下载好
import mysql.connector
cnx = mysql.connector.connect(
user='root', # 数据库的用户名
password='123456', #设置的密码
host='localhost', #主机名,为本地主机,一般默为"localhost"
database='mysql_test', #数据库名字
auth_plugin='mysql_native_password' #默认,不用修改
)
cursor = cnx.cursor()
# 插入数据
add_data = ("INSERT INTO tb_test " #'tb_test'数据表
"(Sno, Sname, Ssex, Sbirthday, Ssalary, Scomm) "
"VALUES (%s, %s, %s, %s, %s, %s, %s)")
data_1 = ('S0001', '张三', 1, '1950-12-30', 10000, 5684.25)
data_2 = ('S0002', '李四', 1, '1952-03-05', 8000, None)
data_3 = ('S0003', '王五', 2, '1962-08-05', 6000, 1235.28)
data_4 = ('S0004', '赵六', 1, '1972-04-21', 4000, 2456.25)
cursor.execute(add_data, data_1)
cursor.execute(add_data, data_2)
cursor.execute(add_data, data_3)
cursor.execute(add_data, data_4)
# 提交更改
cnx.commit()
# 关闭游标和数据库连接
cursor.close()
cnx.close()