把excel文件导入mysql数据库,网络中有一些方法,我最终选用使用python导入,该方法简单有效,介绍如下
工作流程:
第一步:创建数据库
在navicat建立一个数据库,也可以通过代码命令来创建,目的是首先得到一个数据库
创建数据库pr
第二步:准备excel数据表
准备你要导入的目标excel表,并记住路径位置
表内容
表路径及名称
第三步:执行python代码导入
import pymysql ##PyMySQL是在 Python3.x 版本中用于连接 MySQL 服务器的一个库
import pandas as pd ##Pandas是Python的一个数据分析包 导入panda命名为pd
from sqlalchemy import create_engine ## 导入引擎
file = r'C:\Users\lenovo\Desktop\test.xlsx' ## 文件
df = pd.read_excel(file) ## 读文件
## 连接数据库
engine = create_engine("mysql+mysqlconnector://username:password@host:port/database") ## ****代表你的数据库密码
##mysql -- 数据库类型
##mysqlconnector -- 数据库驱动选择
##username -- 数据库用户名
##password -- 用户密码
##host 服务器地址
##port 端口
##database 数据库
df.to_sql('test_new',con=engine,if_exists='replace',index=False) ##导入数据库,如果存在就替换
# if_exists='replace' 如果存在就替换,那追加呢?
#
# if_exists='append'
test_new:数据库上传保存的表名
导入数据库
原理:先用pandas读取excel表格,然后再用pandas保存到mysql数据库
注意:其中执行代码如果遇到报错:
(1)ModuleNotFoundError: No module named 'mysql'
执行代码:
pip install mysql-connector
(2)mysql.connector.errors.NotSupportedError) Authentication plugin 'caching_sha2_password' is not supported
执行代码:
pip install MySQL-connector-python