Ubuntu系统:excel数据导入MySQL数据库

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()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值