如何将 CSV 文件导入 MySQL 表

How to import a CSV file into a MySQL table(如何将 CSV 文件导入 MySQL 表)
本文介绍了如何将 CSV 文件导入 MySQL 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何将 CSV 文件导入 MySQL 表?我想将第一行数据用作列名.

How can I import a CSV file into a MySQL table? I would like for the first row of data be used as the column names.

我阅读了如何将 CSV 文件导入 MySQL 表?,但唯一的答案是使用 GUI 而不是外壳?

I read How do I import CSV file into a MySQL table?, but the only answer was to use a GUI and not a shell?

推荐答案

您可以将 MYSQL 直接链接到它并使用以下 SQL 语法上传信息,而不是编写脚本来从 CSV 文件中提取信息.

Instead of writing a script to pull in information from a CSV file, you can link MYSQL directly to it and upload the information using the following SQL syntax.

>

要将 Excel 文件导入 MySQL,首先将其导出为 CSV 文件.从生成的 CSV 文件中删除 CSV 标题以及 Excel 可能放在 CSV 文件末尾的空数据.

To import an Excel file into MySQL, first export it as a CSV file. Remove the CSV headers from the generated CSV file along with empty data that Excel may have put at the end of the CSV file.

然后您可以通过运行将其导入到 MySQL 表中:

You can then import it into a MySQL table by running:

load data local infile 'uniq.csv' into table tblUniq fields terminated by ','
  enclosed by '"'
  lines terminated by '\n'
    (uniqName, uniqCity, uniqComments)

阅读:将 CSV 文件直接导入 MySQL

对于您的情况,您需要先编写一个解释器,用于查找第一行并将它们指定为列名.

For your case, you'll need to write an interpreter first, for finding the first row, and assigning them as column names.

来自 MySQL 文档 关于 LOAD DATA 语法:

From MySQL docs on LOAD DATA syntax:

IGNORE number LINES 选项可用于忽略在文件的开头.例如,您可以使用 IGNORE 1 LINES 跳过在包含列名的初始标题行上:

The IGNORE number LINES option can be used to ignore lines at the start of the file. For example, you can use IGNORE 1 LINES to skip over an initial header line containing column names:

LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test IGNORE 1 LINES;

因此,您可以使用以下语句:

Therefore, you can use the following statement:

LOAD DATA LOCAL INFILE 'uniq.csv'
INTO TABLE tblUniq
FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(uniqName, uniqCity, uniqComments)

这篇关于如何将 CSV 文件导入 MySQL 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Why Mysql#39;s Group By and Oracle#39;s Group by behaviours are different(为什么 Mysql 的 Group By 和 Oracle 的 Group by 行为不同)
MySQL GROUP BY DateTime +/- 3 seconds(MySQL GROUP BY DateTime +/- 3 秒)