终端pip install mysql-connector安装库
# coding: utf-8
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user='root',
password='123456',
database='covid_19_data'
)
cursor = conn.cursor()
cursor.execute('create table time_series_19_covid_combined(Country_Region varchar(20),Province_State varchar(20),Date_value date,Confirmed integer,Recovered integer,Deaths integer,primary key (Country_Region, Province_State, Date_value))')
首次尝试,报错“authentication plugin 'calling_sha2_password' is not supported.”。
原因:MySQL 的 8.0 版本,密码插件验证方式发生了变化,早期版本为 mysql_native_password,8.0 版本为 caching_sha2_password。
解决:1. 修改 my.ini 配置。2. 在 mysql 下执行命令来修改密码。
插曲:忘了mysql安装位置,查询
select @@basedir as basePath from dual
1. 修改my.ini 配置,添加如下语句:
# 设置密码插件验证方式
default_authentication_plugin=mysql_native_password
2. 在 mysql 下执行如下命令来修改密码(用户名和密码要修改为自己的):
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
3. 连接时声明auth_plugin='mysql_native_password'
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user='root',
password='123456',
database='covid_19_data',
auth_plugin='mysql_native_password'
)
cursor = conn.cursor()
cursor.execute('create table time_series_19_covid_combined(Country_Region varchar(20),Province_State varchar(20),Date_value date,Confirmed integer,Recovered integer,Deaths integer,primary key (Country_Region, Province_State, Date_value))')
成功运行。
pycharm在SQL语句行显示“no data sources are configured to run this SQL”,添加数据库的连接配置可以消除这一提示。
点击右侧边栏Database,添加Data Source,配置时填入user, password, 在URL末尾加上?serverTimezone=UTC。
点击OK,返回就不再显示no data sources提示了。
参考:https://blog.csdn.net/wxhjw507/article/details/107341015
https://blog.csdn.net/weixin_42856871/article/details/104587553