如何将 CSV 文件导入 MySQL 表?

发布于 2024-09-17 17:44:37 字数 1644 浏览 7 评论 0 原文

我有一个来自客户端的非标准化事件日记 CSV,我正在尝试将其加载到 MySQL 表中,以便我可以重构为正常的格式。我创建了一个名为“CSVImport”的表,其中 CSV 文件的每一列都有一个字段。 CSV 包含 99 列,因此这本身就是一项艰巨的任务:

CREATE TABLE 'CSVImport' (id INT);
ALTER TABLE CSVImport ADD COLUMN Title VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN Company VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN NumTickets VARCHAR(256);
...
ALTER TABLE CSVImport Date49 ADD COLUMN Date49 VARCHAR(256);
ALTER TABLE CSVImport Date50 ADD COLUMN Date50 VARCHAR(256);

表上没有任何约束,并且所有字段都保存 VARCHAR(256) 值,除了包含计数的列(由 INT 表示),是/否(由 BIT 表示)、价格(由 DECIMAL 表示)和文本简介(由 TEXT 表示)。

我尝试将数据加载到文件中:

LOAD DATA INFILE '/home/paul/clientdata.csv' INTO TABLE CSVImport;
Query OK, 2023 rows affected, 65535 warnings (0.08 sec)
Records: 2023  Deleted: 0  Skipped: 0  Warnings: 198256
SELECT * FROM CSVImport;
| NULL             | NULL        | NULL           | NULL | NULL               | 
...

整个表都充满了NULL

我认为问题在于文本简介包含不止一行,并且 MySQL 正在解析该文件,就好像每一新行都对应于一个数据库行。我可以毫无问题地将文件加载到 OpenOffice 中。

clientdata.csv 文件包含 2593 行和 570 条记录。第一行包含列名称。我认为它是逗号分隔的,文本显然是用双引号分隔的。

更新:

如有疑问,请阅读手册: http://dev .mysql.com/doc/refman/5.0/en/load-data.html

我向 OpenOffice 足够智能的 LOAD DATA 语句添加了一些信息,现在它会加载正确的记录数:

LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

但是仍然有很多完全 NULL 记录,并且加载的数据似乎都没有位于正确的位置。

I have an unnormalized events-diary CSV from a client that I'm trying to load into a MySQL table so that I can refactor into a sane format. I created a table called 'CSVImport' that has one field for every column of the CSV file. The CSV contains 99 columns , so this was a hard enough task in itself:

CREATE TABLE 'CSVImport' (id INT);
ALTER TABLE CSVImport ADD COLUMN Title VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN Company VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN NumTickets VARCHAR(256);
...
ALTER TABLE CSVImport Date49 ADD COLUMN Date49 VARCHAR(256);
ALTER TABLE CSVImport Date50 ADD COLUMN Date50 VARCHAR(256);

No constraints are on the table, and all the fields hold VARCHAR(256) values, except the columns which contain counts (represented by INT), yes/no (represented by BIT), prices (represented by DECIMAL), and text blurbs (represented by TEXT).

I tried to load data into the file:

LOAD DATA INFILE '/home/paul/clientdata.csv' INTO TABLE CSVImport;
Query OK, 2023 rows affected, 65535 warnings (0.08 sec)
Records: 2023  Deleted: 0  Skipped: 0  Warnings: 198256
SELECT * FROM CSVImport;
| NULL             | NULL        | NULL           | NULL | NULL               | 
...

The whole table is filled with NULL.

I think the problem is that the text blurbs contain more than one line, and MySQL is parsing the file as if each new line would correspond to one databazse row. I can load the file into OpenOffice without a problem.

The clientdata.csv file contains 2593 lines, and 570 records. The first line contains column names. I think it is comma delimited, and text is apparently delimited with doublequote.

UPDATE:

When in doubt, read the manual: http://dev.mysql.com/doc/refman/5.0/en/load-data.html

I added some information to the LOAD DATA statement that OpenOffice was smart enough to infer, and now it loads the correct number of records:

LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

But still there are lots of completely NULL records, and none of the data that got loaded seems to be in the right place.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

小…红帽 2024-09-24 17:44:37

使用 mysqlimport 将表加载到数据库中:

mysqlimport --ignore-lines=1 \
            --fields-terminated-by=, \
            --local -u root \
            -p Database \
             TableName.csv

我在 < a href="http://chriseiffel.com/everything-linux/how-to-import-a-large-csv-file-to-mysql/" rel="noreferrer">http://chriseiffel.com/everything -linux/how-to-import-a-large-csv-file-to-mysql/

要使分隔符成为制表符,请使用 --fields-termminate-by='\t'

Use mysqlimport to load a table into the database:

mysqlimport --ignore-lines=1 \
            --fields-terminated-by=, \
            --local -u root \
            -p Database \
             TableName.csv

I found it at http://chriseiffel.com/everything-linux/how-to-import-a-large-csv-file-to-mysql/

To make the delimiter a tab, use --fields-terminated-by='\t'

谢绝鈎搭 2024-09-24 17:44:37

您问题的核心似乎是将 CSV 文件中的列与表中的列进行匹配。

许多图形化的 mySQL 客户端对于此类事情都有非常好的导入对话框。

我最喜欢的工作是基于 Windows 的 HeidiSQL。它为您提供了一个图形界面来构建LOAD DATA命令;您可以稍后以编程方式重复使用它。

导入文本文件

屏幕截图:“导入文本文件”对话框

打开导入文本文件”对话框,转到工具 > 导入 CSV 文件

在此处输入图像描述

The core of your problem seems to be matching the columns in the CSV file to those in the table.

Many graphical mySQL clients have very nice import dialogs for this kind of thing.

My favourite for the job is Windows based HeidiSQL. It gives you a graphical interface to build the LOAD DATA command; you can re-use it programmatically later.

Import textfile

Screenshot: "Import textfile" dialog

To open the Import textfile" dialog, go to Tools > Import CSV file:

enter image description here

定格我的天空 2024-09-24 17:44:37

我导入 200 多行的最简单方法是在 phpmyadmin sql 窗口中的命令下方

我有一个包含两列的简单国家/地区表
CountryId,CountryName

这里是 .csv 数据CSV FILE

这里是命令:

LOAD DATA INFILE 'c:/country.csv' 
INTO TABLE country 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS

记住一件事,永远不要出现在第二列中,否则你的导入将会停止

Simplest way which I have imported 200+ rows is below command in phpmyadmin sql window

I have a simple table of country with two columns
CountryId,CountryName

here is .csv dataCSV FILE

here is command:

LOAD DATA INFILE 'c:/country.csv' 
INTO TABLE country 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS

Keep one thing in mind, never appear , in second column, otherwise your import will stop

又怨 2024-09-24 17:44:37

我使用此方法在 0.046sec 内导入了超过 100K 记录 (~5MB),

具体操作方法如下:

LOAD DATA LOCAL INFILE  
'c:/temp/some-file.csv'
INTO TABLE your_awesome_table  
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(field_1,field_2 , field_3);

如果您有,包含最后一行非常重要多个字段,即通常它会跳过最后一个字段(MySQL 5.6.17)

LINES TERMINATED BY '\n'
(field_1,field_2 , field_3);

然后,假设您将第一行作为字段的标题,您可能还想包含这一行

IGNORE 1 ROWS

这就是看起来您的文件是否有标题行。

LOAD DATA LOCAL INFILE  
'c:/temp/some-file.csv'
INTO TABLE your_awesome_table  
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(field_1,field_2 , field_3);

I Used this method to import more than 100K records (~5MB) in 0.046sec

Here's how you do it:

LOAD DATA LOCAL INFILE  
'c:/temp/some-file.csv'
INTO TABLE your_awesome_table  
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(field_1,field_2 , field_3);

It is very important to include the last line , if you have more than one field i.e normally it skips the last field (MySQL 5.6.17)

LINES TERMINATED BY '\n'
(field_1,field_2 , field_3);

Then, assuming you have the first row as the title for your fields, you might want to include this line also

IGNORE 1 ROWS

This is what it looks like if your file has a header row.

LOAD DATA LOCAL INFILE  
'c:/temp/some-file.csv'
INTO TABLE your_awesome_table  
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(field_1,field_2 , field_3);
我只土不豪 2024-09-24 17:44:37

phpMyAdmin可以处理CSV导入。步骤如下:

  1. 准备 CSV 文件,使其字段的顺序与 MySQL 表字段的顺序相同。

  2. 从 CSV 中删除标题行(如果有),以便文件中只有数据。

  3. 进入phpMyAdmin界面。

  4. 在左侧菜单中选择表格。

  5. 单击顶部的导入按钮。

  6. 浏览到 CSV 文件。

  7. 选择选项“使用加载数据的 CSV”。

  8. 在“字段终止于”中输入“,”。

  9. 按照数据库表中的顺序输入列名。

  10. 单击“执行”按钮即可完成。

这是我为将来使用而准备的笔记,如果其他人可以受益的话,请在此分享。

phpMyAdmin can handle CSV import. Here are the steps:

  1. Prepare the CSV file to have the fields in the same order as the MySQL table fields.

  2. Remove the header row from the CSV (if any), so that only the data is in the file.

  3. Go to the phpMyAdmin interface.

  4. Select the table in the left menu.

  5. Click the import button at the top.

  6. Browse to the CSV file.

  7. Select the option "CSV using LOAD DATA".

  8. Enter "," in the "fields terminated by".

  9. Enter the column names in the same order as they are in the database table.

  10. Click the go button and you are done.

This is a note that I prepared for my future use, and sharing here if someone else can benefit.

双手揣兜 2024-09-24 17:44:37

如果您使用 MySQL Workbench(当前为 6.3 版本),您可以通过以下方式执行此操作:

  1. 右键单击​​“Tables”;
  2. 选择表数据导入向导;
  3. 选择您的 csv 文件并按照说明进行操作(也可以使用 JSON);
    好处是,您可以根据要导入的 csv 文件创建新表或将数据加载到现有表

在此处输入图像描述

If you are using MySQL Workbench (currently 6.3 version) you can do this by:

  1. Right click on "Tables";
  2. Chose Table Data Import Wizard;
  3. Chose your csv file and follow the instructions (JSON also could be used);
    The good thing is that you can create a new table based on the csv file you want to import or load data to an existing table

enter image description here

随心而道 2024-09-24 17:44:37

您可以通过列出 LOAD DATA 语句中的列来解决此问题。从手册

LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata (col1,col2,...);

...所以在您的情况下,您需要列出99 列,按照它们在 csv 文件中出现的顺序排列。

You can fix this by listing the columns in you LOAD DATA statement. From the manual:

LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata (col1,col2,...);

...so in your case you need to list the 99 columns in the order in which they appear in the csv file.

苹果你个爱泡泡 2024-09-24 17:44:37

试试这个,它对我有用

    LOAD DATA LOCAL INFILE 'filename.csv' INTO TABLE table_name FIELDS TERMINATED BY ',' ENCLOSED BY '"' IGNORE 1 ROWS;

IGNORE 1 ROWS 这里忽略包含字段名的第一行。请注意,对于文件名,您必须键入文件的绝对路径。

Try this, it worked for me

    LOAD DATA LOCAL INFILE 'filename.csv' INTO TABLE table_name FIELDS TERMINATED BY ',' ENCLOSED BY '"' IGNORE 1 ROWS;

IGNORE 1 ROWS here ignores the first row which contains the fieldnames. Note that for the filename you must type the absolute path of the file.

未央 2024-09-24 17:44:37

我看到一些奇怪的东西。用于 ESCAPING 的字符与用于 ENCLOSING 的字符相同。因此,当引擎发现“”时,它不知道该怎么做,我认为这就是为什么似乎没有什么东西在正确的位置。
我认为如果你删除 ESCAPING 行,应该运行得很好。例如:

LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

除非您分析(手动、直观地……)您的 CSV 并找到哪个字符用于转义。有时是“\”。但如果您没有它,请不要使用它。

I see something strange. You are using for ESCAPING the same character you use for ENCLOSING. So the engine does not know what to do when it founds a '"' and I think that is why nothing seems to be in the right place.
I think that if you remove the line of ESCAPING, should run great. Like:

LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

Unless you analyze (manually, visually, ... ) your CSV and find which character uses for escape. Sometimes is '\'. But if you do not have it, do not use it.

若有似无的小暗淡 2024-09-24 17:44:37

mysql命令行导入时容易出现太多问题。操作方法如下:

  • 使用 Excel 编辑标题名称,使其不包含空格,
  • 另存为 .csv
  • 使用免费的 Navicat Lite Sql 浏览器导入并自动创建新表(为其命名)
  • 打开新表插入主自动表ID 的数字列
  • 根据需要更改列的类型。
  • 完毕!

The mysql command line is prone to too many problems on import. Here is how you do it:

  • use excel to edit the header names to have no spaces
  • save as .csv
  • use free Navicat Lite Sql Browser to import and auto create a new table (give it a name)
  • open the new table insert a primary auto number column for ID
  • change the type of the columns as desired.
  • done!
<逆流佳人身旁 2024-09-24 17:44:37

另一种解决方案是使用来自令人惊叹的 csvsql 工具https://github.com/wireservice/csvkit" rel="noreferrer">csvkit 套件。

使用示例:

csvsql --db mysql://$user:$password@localhost/$database --insert --tables $tablename  $file

该工具可以自动推断数据类型(默认行为)、创建表并将数据插入到创建的表中。 --overwrite 选项可用于删除表(如果已存在)。 --insert 选项 — 从文件填充表。

安装套件

pip install csvkit

先决条件: python-devlibmysqlclient-devMySQL-python

apt-get install python-dev libmysqlclient-dev
pip install MySQL-python

Yet another solution is to use csvsql tool from amazing csvkit suite.

Usage example:

csvsql --db mysql://$user:$password@localhost/$database --insert --tables $tablename  $file

This tool can automatically infer the data types (default behavior), create table and insert the data into the created table. --overwrite option can be used to drop table if it already exists. --insert option — to populate the table from the file.

To install the suite

pip install csvkit

Prerequisites: python-dev, libmysqlclient-dev, MySQL-python

apt-get install python-dev libmysqlclient-dev
pip install MySQL-python
诗酒趁年少 2024-09-24 17:44:37

如果您使用的是加载了 Excel 电子表格的 Windows 计算机,那么 Excel 的新 mySql 插件将是惊人的。 Oracle 的人员在该软件上确实做得很好。您可以直接从 Excel 建立数据库连接。该插件将分析您的数据,并以与数据一致的格式为您设置表格。我有一些巨大的 csv 文件需要转换。这个工具可以节省大量时间。

http://dev.mysql.com/downloads/windows/excel/

你可以从 Excel 中进行更新,并将其在线填充到数据库中。这对于在超便宜的 GoDaddy 共享主机上创建的 mySql 文件非常有效。 (请注意,当您在 GoDaddy 创建表时,您必须选择一些非标准设置才能启用数据库的异地访问...)

使用此插件,您可以在 XL 电子表格和在线 mySql 数据存储之间实现纯粹的交互。

If you are using a windows machine with Excel spreadsheet loaded, the new mySql plugin to Excel is phenomenal. The folks at Oracle really did a nice job on that software. You can make the database connection directly from Excel. That plugin will analyse your data, and set up the tables for you in a format consistent with the data. I had some monster big csv files of data to convert. This tool was a big time saver.

http://dev.mysql.com/downloads/windows/excel/

You can make updates from within Excel that will populate to the database online. This worked exceedingly well with mySql files created on ultra inexpensive GoDaddy shared hosting. (Note when you create the table at GoDaddy, you have to select some off-standard settings to enable off site access of the database...)

With this plugin you have pure interactivity between your XL spreadsheet and online mySql data storage.

蓦然回首 2024-09-24 17:44:37

我使用 mysql workbench 来做同样的工作。

  1. 创建新架构
  2. 打开新创建的架构
  3. 右键单击​​“表”并选择“表数据导入向导”
  4. 提供 csv 文件路径和表名称,最后配置列类型,因为向导根据其值设置默认列类型。

注意:使用“tail -f [mysqlworkbenchpath]/log/wb*.log”查看 mysql 工作台的日志文件中是否有任何错误

I use mysql workbench to do the same job.

  1. create new schema
  2. open newly created schema
  3. right click on "Tables" and select "Table Data Import Wizard"
  4. give the csv file path and table name and finally configure your column type because the wizard set default column type based on their values.

Note: take a look at mysql workbench's log file for any errors by using "tail -f [mysqlworkbenchpath]/log/wb*.log"

极致的悲 2024-09-24 17:44:37

如何将 csv 文件导入 sql 表

示例文件:Overseas_trade_index 数据 CSV 文件

步骤:

  1. 需要为 overseas_trade_index 创建表。

  2. 需要创建与csv文件相关的列。

    SQL 查询:

    ( id int not null 主键自动增量,
    系列参考 varchar (60),
    时期 varchar (60),
    数据值十进制(60,0),
    状态 varchar (60),
    单位 varchar (60),
    震级 int(60),
    主题文本(60),
    组文本(60),
    Series_title_1 varchar (60),
    Series_title_2 varchar (60),
    Series_title_3 varchar (60),
    Series_title_4 varchar (60),
    Series_title_5 varchar (60),
     );
    
  3. 需要在终端连接mysql数据库。

    =>显示数据库;
    =>使用数据库;
    =>显示表格;
    
  4. 请输入此命令将csv数据导入mysql表。

    将文件“/home/desktop/Documents/overseas.csv”中的数据加载到以“,”结尾的表 trade_index 字段中,以“\n”结尾的行(series_reference、period、data_value、status、units、magnitude、主题、系列标题1、系列标题_2、系列标题_3、系列标题_4、系列标题_5);
    
  5. 在sqldatabase上查找该海外贸易指数数据:

    从 trade_index 中选择*;
    

How to import csv files to sql tables

Example file: Overseas_trade_index data CSV File

Steps:

  1. Need to create table for overseas_trade_index.

  2. Need to create columns related to csv file.

    SQL Query:

    ( id int not null primary key auto_increment,
    series_reference varchar (60),
    period varchar (60),
    data_value decimal(60,0),
    status varchar (60),
    units varchar (60),
    magnitude int(60),
    subject text(60),
    group text(60),
    series_title_1 varchar (60),
    series_title_2 varchar (60),
    series_title_3 varchar (60),
    series_title_4 varchar (60),
    series_title_5 varchar (60),
     );
    
  3. Need to connect mysql database in terminal.

    =>show databases;
    =>use database;
    =>show tables;
    
  4. Please enter this command to import the csv data to mysql tables.

    load data infile '/home/desktop/Documents/overseas.csv' into table trade_index fields terminated by ',' lines terminated by '\n' (series_reference,period,data_value,status,units,magnitude,subject,series_title1,series_title_2,series_title_3,series_title_4,series_title_5);
    
  5. Find this overseas trade index data on sqldatabase:

    select * from trade_index;
    
说不完的你爱 2024-09-24 17:44:37

我知道我的回答已经晚了,但我想提一下其他一些方法。
最简单的一种是使用命令行。步骤如下:

  1. 输入以下命令访问 MySQL CLI:

mysql -u my_user_name -p

  1. 在数据库中创建表
使用new_schema;

创建表员工详细信息(
id 整数,
员工姓名 VARCHAR(100),
员工年龄 INTEGER,
主键(id)
);
  1. 将 CSV 文件导入到表中。我们可以指定文件路径或将文件存储在 MySQL 服务器的默认目录中。
LOAD DATA INFILE '导出的 csv 文件的路径'
INTO表employee_details
以“,”结尾的字段
忽略 1 行;

这是众多解决方案中唯一的一个,我在这个 教程
如果将 CSV 文件加载到 MySQL 数据库是您的日常任务,那么最好自动化此过程。在这种情况下,您可以使用一些第三方工具来按计划加载数据。

I know that my answer is late, but I'd like to mention a few other ways to do it.
The easiest one is using command line. The steps will be the following:

  1. Accessing the MySQL CLI by entering the below command:

mysql -u my_user_name -p

  1. Creating a table in the database
use new_schema;

CREATE TABLE employee_details (
id INTEGER,
employee_name VARCHAR(100),
employee_age INTEGER,
PRIMARY KEY (id)
);
  1. Importing the CSV file into a table. We can either mention the file path or store the file in the default directory of the MySQL server.
LOAD DATA INFILE 'Path to the exported csv file'
INTO TABLE employee_details
FIELDS TERMINATED BY ','
IGNORE 1 ROWS;

It's the only one of many solutions, I found it in this tutorial
If loading CSV files into MySQL database is your daily task, then it'll be better to automate this process. In this case you can use some 3rd-party tools that allows you to load data in schedule.

太阳哥哥 2024-09-24 17:44:37

我使用 phpmyadmin 以简单的方式完成了它。我按照@Farhan 的步骤操作,但所有数据都在单列​​中进行了更改。
我是如何做的:

  1. 创建一个 CSV 文件并删除带有列名称的标题行。仅保留数据。
  2. 我创建了一个表,其列名称与 csv 列匹配。
  3. 请记住为每列分配适当的类型。
  4. 我刚刚选择导入并转到导入选项卡。
  5. 在浏览中,我选择了 CSV 文件并保留所有选项不变。
  6. 令我惊讶的是,所有数据都成功导入到相应的列中。

I did it in simple way using phpmyadmin. I followed the steps by @Farhan but all data were eltered in single column.
How I did:

  1. Created a CSV file and deleted the header row with column names. Kept only data.
  2. I created a table with column names matching the csv columns.
  3. Remember to assign appropriate types to each column.
  4. I just selected the import and went to import tab.
  5. In browse I selected the CSV file and kept all options as it is.
  6. To my surprise all the data got imported successfully in their appropriate columns.
妥活 2024-09-24 17:44:37

PHP 查询导入 csv 文件到 mysql 数据库

$query = <<<EOF
            LOAD DATA LOCAL INFILE '$file'
             INTO TABLE users
             FIELDS TERMINATED BY ','
             LINES TERMINATED BY '\n'
             IGNORE 1 LINES
            (name,mobile,email)
    EOF;
if (!$result = mysqli_query($this->db, $query))
   {
        exit(mysqli_error($this->db));
   }

**示例 CSV 文件数据 **

name,mobile,email
Christopher Gritton,570-686-3439,[email protected]
Brandon Wilson,541-309-5149,[email protected]
Craig White,516-795-8065,[email protected]
David Whitney,713-214-3966,[email protected]

PHP Query for import csv file to mysql database

$query = <<<EOF
            LOAD DATA LOCAL INFILE '$file'
             INTO TABLE users
             FIELDS TERMINATED BY ','
             LINES TERMINATED BY '\n'
             IGNORE 1 LINES
            (name,mobile,email)
    EOF;
if (!$result = mysqli_query($this->db, $query))
   {
        exit(mysqli_error($this->db));
   }

**Sample CSV file data **

name,mobile,email
Christopher Gritton,570-686-3439,[email protected]
Brandon Wilson,541-309-5149,[email protected]
Craig White,516-795-8065,[email protected]
David Whitney,713-214-3966,[email protected]
纸伞微斜 2024-09-24 17:44:37

以下是示例 Excel 文件屏幕截图:

在此处输入图像描述

另存为并选择 .csv。

如果使用记事本++或任何其他记事本打开,您将获得如下所示的.csv数据屏幕截图。

输入图片这里的描述

确保删除标题并在 .csv 中像 mysql 表一样进行列对齐。
将folder_name 替换为您的文件夹名称

LOAD DATA LOCAL INFILE
'D:/文件夹名称/myfilename.csv'
进入表邮件
以“,”结尾的字段
(fname,lname,email,phone);

如果数据量很大,你可以喝咖啡然后加载它!

这就是你所需要的。

Here is sample excel file screen shot:

enter image description here

Save as and choose .csv.

And you will have as shown below .csv data screen shot if you open using notepad++ or any other notepad.

enter image description here

Make sure you remove header and have column alignment in .csv as in mysql Table.
Replace folder_name by your folder name

LOAD DATA LOCAL INFILE
'D:/folder_name/myfilename.csv'
INTO TABLE mail
FIELDS TERMINATED BY ','
(fname,lname ,email, phone);

If big data, you can take coffee and have it load!.

Thats all you need.

秋风の叶未落 2024-09-24 17:44:37

更改服务器名、用户名、密码、数据库名、文件路径、表名以及要插入的数据库中的字段

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "bd_dashboard";
    //For create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    $query = "LOAD DATA LOCAL INFILE 
                'C:/Users/lenovo/Desktop/my_data.csv'
                INTO TABLE test_tab
                FIELDS TERMINATED BY ','
                LINES TERMINATED BY '\n'
                IGNORE 1 LINES
                (name,mob)";
    if (!$result = mysqli_query($conn, $query)){
        echo '<script>alert("Oops... Some Error occured.");</script>';
        exit();
            //exit(mysqli_error());
       }else{
        echo '<script>alert("Data Inserted Successfully.");</script>'
       }
    ?>

Change servername,username, password,dbname,path of your file, tablename and the field which is in your database you want to insert

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "bd_dashboard";
    //For create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    $query = "LOAD DATA LOCAL INFILE 
                'C:/Users/lenovo/Desktop/my_data.csv'
                INTO TABLE test_tab
                FIELDS TERMINATED BY ','
                LINES TERMINATED BY '\n'
                IGNORE 1 LINES
                (name,mob)";
    if (!$result = mysqli_query($conn, $query)){
        echo '<script>alert("Oops... Some Error occured.");</script>';
        exit();
            //exit(mysqli_error());
       }else{
        echo '<script>alert("Data Inserted Successfully.");</script>'
       }
    ?>
温馨耳语 2024-09-24 17:44:37

执行 MySQL 查询导入 CSV 时出现错误
'错误代码:1290。MySQL 服务器正在使用 --secure-file-priv 选项运行,因此无法执行此语句'

因此我将文件移动到安全文件位置,

LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/Orders.csv'   
INTO TABLE orderdetails.orders 
FIELDS TERMINATED BY ','  
 ENCLOSED BY '"'
 LINES TERMINATED BY '\n'
 IGNORE 1 ROWS

其中文件位置为“C” :/ProgramData/MySQL/MySQL Server 8.0/Uploads/Orders.csv' 这是因为,我将 CSV 文件移动到了 'secure_file_priv' 位置,否则我收到上述错误

您可以使用查询 SHOW VARIABLES LIKE " 获取 secure_file_priv secure_file_priv";

来源:将 CSV 文件导入 MySQL(查询或使用 Workbench)

When executing MySQL Query to import CSV I was getting error
'Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement'

So I moved file to secure file location

LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/Orders.csv'   
INTO TABLE orderdetails.orders 
FIELDS TERMINATED BY ','  
 ENCLOSED BY '"'
 LINES TERMINATED BY '\n'
 IGNORE 1 ROWS

Where location of file is 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/Orders.csv' this is because, I moved my CSV file to 'secure_file_priv' location otherwise I was getting above error

You can get your secure_file_priv using query SHOW VARIABLES LIKE "secure_file_priv";

Source: Import CSV file to MySQL (Query or using Workbench)

酸甜透明夹心 2024-09-24 17:44:37

您好,使用 use teminal 将 csv 导入您的 mysql 数据库,因为如果
数据集很大,那么很难从文件上传选项导入数据。

基本上我们首先使用表导入数据,然后在数据库中创建表。
提交同一个表后,我们必须从 csv 创建数据。

您必须添加 csv 文件 导航到以下目录:/var/lib/mysql-files 但如果您不使用 root 用户,那么它不能直接转到 /var/lib/mysql -files 所以使用 ui 首先转到 /var/lib 然后
单击mysql-files,然后输入您的 root 用户密码。然后复制
我们在表中导入的 csv 文件。

在 termianl 中登录 mysql 并选择数据库后,然后在下面触发
syntex 数据

LOAD DATA INFILE '/var/lib/mysql-files/{your-csv-name}'
INTO TABLE {your-table-name}
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

例如,我的表是示例,mycsv 文件是 Sample.csv,然后如下
参考

LOAD DATA INFILE '/var/lib/mysql-files/Sample.csv' INTO TABLE sample FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;

对于导入大量 csv,最好的方法是使用 mysql 终端
将数据导入数据库中。

请检查此链接的示例:Mysql使用终端或命令行使用csv导入数据

Hi Import csv in your mysql database using use teminal because if
data set in large then it's difficult to import data from file upload options.

Basically We have import data using table first create table in database.
after same table filed we have to create data from csv.

You have to add csv file Navigate to the following directory: /var/lib/mysql-files but if you not use root user then it can not direct goes to /var/lib/mysql-files so using ui first go to /var/lib then
click on mysql-files then enter your root user password. then copy the
your csv file which we import in table.

after you are login mysql in termianl and databse selected then fire below
syntex data

LOAD DATA INFILE '/var/lib/mysql-files/{your-csv-name}'
INTO TABLE {your-table-name}
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

For Example my table is sample and mycsv file is Sample.csv then below
reference

LOAD DATA INFILE '/var/lib/mysql-files/Sample.csv' INTO TABLE sample FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;

For importing large amount of csv it's best way to use mysql terminal for
importing data in your database.

Please check sample for this link : Mysql import data using csv using terminal or command line

最单纯的乌龟 2024-09-24 17:44:37

喜欢使用 HeidiSQL 接受的答案。现在有很多选项可以将 CSV 文件导入 MySQL。提问者的文本/字符串列格式很奇怪。所以,我也想尝试一下。
我将使用另一个选项,它也是 GUI,但基于云。根据您的 MySQL 实例所在的位置,您是否需要安装某些内容。如果它在云中,则无需安装任何内容。如果它位于本地且无法通过 Internet 访问,则您需要一个客户端应用程序来将该工具连接到它。
现在,云中有很多数据集成工具,但我将使用我熟悉的一个 Skyvia。再次强调,您并不局限于此特定产品。
假设我有以下 CSV 文件,其中包含 3 列“姓名”、“出生日期”和“备注”。

Book1。 正如您所看到的, csv

有换行符,有些用引号引起来,有些则没有。
由于我的笔记本电脑上有 MySQL 实例,因此我必须安装 Skyvia Agent 以安全地允许 Skyvia 访问数据并将数据写入其中。下面显示正在运行:
input_agent_key

目标表是这样的:

create table testdatabase.csvdump
(
  name varchar(50) default null
, birthdate date default null
, remarks varchar(255) default null
)
engine = innodb,
character set utf8mb4,
collate utf8mb4_0900_ai_ci;

在 Skyvia 中,我使用代理创建了一个连接。
mysql_agent

然后,我创建了一个导入作业,如下所示:
import_workspace

我使用了之前创建的 MySQL 连接。然后,我创建了一个任务来获取 CSV,对其进行一些配置,并将列映射到 MySQL。我只是简单一点,所以我只上传了 CSV 文件,但它可以来自 Google Drive、Onedrive 等。请参阅下面的源定义:

task_editor_step1

然后在下面,我指定了目标表以及要使用的操作(Insert 、更新等)

task_editor_step2

然后,我将 CSV 的列映射到表中。无需人工干预即可很好地绘制地图。请参阅以下结果:

task_editor_step3

然后,我保存了任务和导入集成。
最后,我单击“运行”并等待了几秒钟。
这是我选择它时的结果:

explorer

导入进展顺利。

如果需要无人值守执行,可以安排导入集成定期运行。

LOAD INFILE 很好,但我必须找出正确的语法。如果这种事情是您大部分时间的工作,并且您也需要节省时间来让下一次集成工作,那么上述内容很好。

这是我的工具集中的另一个选项。您可以选择类似的工具或对其进行编码。有多种选择是件好事。

希望这有帮助。

Loved the accepted answer using HeidiSQL. There are many options these days that you can import a CSV file to MySQL. The asker has a strange format of a text/string column. So, I want to try it too.
I’ll be using another option which is also GUI but cloud-based. Depending on where your MySQL instance is, you need to install something or not. If it’s in the cloud, there’s nothing to install. If it’s on-premises and not available over the internet, you need a client application that will connect the tool to it.
Now, there are many data integration tools in the cloud but I’ll be using the one I’m familiar with which is Skyvia. Again, you are not limited to this specific product.
Let’s say I have the following CSV file with 3 columns Name, BirthDate, and Remarks.

Book1.csv

As you can see, there are line feeds and there are some enclosed in quotes and some have not.
Since I have the MySQL instance on my laptop, I have to install the Skyvia Agent to securely allow Skyvia to access and write the data into it. Below it is shown running:
input_agent_key

The target table is this:

create table testdatabase.csvdump
(
  name varchar(50) default null
, birthdate date default null
, remarks varchar(255) default null
)
engine = innodb,
character set utf8mb4,
collate utf8mb4_0900_ai_ci;

And in Skyvia, I created a connection using the Agent.
mysql_agent

Then, I created an Import job shown below:
import_workspace

I used the MySQL connection I created earlier. Then, I created a task to get the CSV, configure it a little, and map the columns to MySQL. I just made it simple so I only uploaded the CSV file but it can come from Google Drive, Onedrive, etc. See the Source definition below:

task_editor_step1

Then below, I specified the target table and what operation to use (Insert, Update, etc.)

task_editor_step2

Then, I mapped the columns of the CSV to the table. It mapped nicely without manual intervention. See the result below:

task_editor_step3

Then, I saved the Task and the Import integration.
Finally, I clicked Run and waited a few seconds.
Here’s the result when I SELECT it:

explorer

The import went well.

The Import integration can be scheduled to run periodically if an unattended execution is needed.

The LOAD INFILE is good though I have to figure out the correct syntax. The above is good if this kind of stuff is your work most of the time and you need to save time to get the next integration working too.

This is another option in my toolset. You can choose a similar tool or code it. It’s good to have several options.

Hope this helps.

迷途知返 2024-09-24 17:44:37

使用 mysqlimport 从 csv 导入数据设置起来很棘手,但一旦完成就可以顺利运行。

假设您有一个具有以下结构的 csv:

jourid,acctid,revid,byto,amount,linenum,adjusted,cleared,version
100888,101019,101001,1,100.00,1,0,0,0
100888,101666,101001,1,200.00,2,0,0,0
100888,101001,101666,-1,300.00,3,0,0,0

首先创建一个要删除的 sql,并在数据库中创建要导入的表。让文件为“tabvoucher.sql”。它应该命名为向表名

tabvoucher.sql 添加 sql 扩展:

drop table if exists tabvoucher;

create table tabvoucher (
  `jourid` int unsigned, 
  `acctid` int unsigned, 
  `revid` int unsigned, 
  `byto` int, 
  `amount` decimal(30, 2), 
  `linenum` int, 
  `adjusted` tinyint, 
  `cleared` tinyint, 
  `version` int
);

然后运行命令:

mysql -u{username} -p{password} --host={localhost} --port={port} {database} < \path\to\tabvoucher.sql

将 {} 中的字段替换为您的登录名和数据库详细信息。请勿包含 { 和 }。
确保表已成功创建。

现在运行 mysqlimport

mysqlimport -d --ignore-lines=1 -h {localhost} --port {port} -u{username} -p{password} --fields-terminated-by=, --fields-enclosed-by=\" --fields-escaped-by=\" --lines-terminated-by=\r\n tutorial \path\to\tabvoucher.csv -v --columns=`jourid`,`acctid`,`revid`,`byto`,`amount`,`linenum`,`adjusted`,`cleared`,`version`

验证所有 --fields* 是否设置正确。
您必须指定 --columns 从 csv 第一行复制列表并为所有字段添加分隔符 `。

您应该得到类似于以下内容的输出:

Connecting to localhost
Selecting database tutorial
Deleting the old data from table tabvoucher
Loading data from SERVER file: path\to\tabvoucher.csv into tabvoucher
tutorial.tabvoucher: Records: 3  Deleted: 0  Skipped: 0  Warnings: 0
Disconnecting from localhost

Using mysqlimport to import data from csv is tricky to set up but runs smoothely once you have done.

Assume you have a csv with the following structure:

jourid,acctid,revid,byto,amount,linenum,adjusted,cleared,version
100888,101019,101001,1,100.00,1,0,0,0
100888,101666,101001,1,200.00,2,0,0,0
100888,101001,101666,-1,300.00,3,0,0,0

First create an sql to drop and create the table in the database to import into. Let the file be 'tabvoucher.sql'. It should be named adding an sql extenstion to the table name

tabvoucher.sql:

drop table if exists tabvoucher;

create table tabvoucher (
  `jourid` int unsigned, 
  `acctid` int unsigned, 
  `revid` int unsigned, 
  `byto` int, 
  `amount` decimal(30, 2), 
  `linenum` int, 
  `adjusted` tinyint, 
  `cleared` tinyint, 
  `version` int
);

Then run the command:

mysql -u{username} -p{password} --host={localhost} --port={port} {database} < \path\to\tabvoucher.sql

Replace fields in {} with your login and db details. Do not include { and }.
Make sure that the table was successfully created.

Now run mysqlimport

mysqlimport -d --ignore-lines=1 -h {localhost} --port {port} -u{username} -p{password} --fields-terminated-by=, --fields-enclosed-by=\" --fields-escaped-by=\" --lines-terminated-by=\r\n tutorial \path\to\tabvoucher.csv -v --columns=`jourid`,`acctid`,`revid`,`byto`,`amount`,`linenum`,`adjusted`,`cleared`,`version`

Verify all the --fields* are correctly set.
You have to specify the --columns copying the list from the first line of csv and adding the delimiter ` for all fields.

You should be getting an output similar to the following:

Connecting to localhost
Selecting database tutorial
Deleting the old data from table tabvoucher
Loading data from SERVER file: path\to\tabvoucher.csv into tabvoucher
tutorial.tabvoucher: Records: 3  Deleted: 0  Skipped: 0  Warnings: 0
Disconnecting from localhost
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文