1.csv文件直接导入
使用MySQLworkbench图形化界面:
右键Tables->table data import wizard即可
2.xls/xlsx数据转换为csv文件导入
① 新建空白TXT文档;
② 使用Ubuntu自带的office工具打开TXT文档->复制excel表中的数据;
③ 将文件另存为csv文件;
④ csv文件的导入与第一种情况相同.
3.Python读取excel数据并写入数据库中
若以上两种情况仍不能成功导入,可使用Python读取数据
Python代码实现如下所示:
import pymysql.cursors
import xlrd
# 连接数据库
connection = pymysql.connect(host='localhost', # 数据库地址
user='root', # 数据库用户名
password='***', # 数据库密码
db='recipes', # 数据库名称
charset='utf8')
cursor = connection.cursor()
# 创建表
sql = "create table Foods (食谱ID int, 编号 char(5), 菜谱名 varchar(20), 来源 varchar(20))"
cursor.execute("drop table if exists Foods")
cursor.execute(sql)
connection.commit()
wb = xlrd.open_workbook('foods.xlsx')
table = wb.sheet_by_name('Sheet1')
thissql = 'insert into Foods values'
for row in range(table.nrows):
value = '('
for col in range(0, 4):
value += "'"+str(table.cell(row, col).value)+"',"
value = value[:(len(value) - 1)] + "),"
thissql += value
#print(row, thissql)
thissql = thissql[:(len(thissql))]
cursor.execute(thissql[:-1])
connection.commit()
print('批量导入数据完毕,共导入:', table.nrows, '条数据')
# 关闭数据库
connection.close()