批处理脚本通过csv文件循环到mysql中

bweufnob  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(249)

如何循环浏览目录中的文件(它们都是csv文件),然后使用登录mysql mysql -u root (为了简单起见没有密码)并将它们全部添加到mysql表中?这是将文件快速加载到mysql的查询:

LOAD DATA LOCAL INFILE "C:/prog/mydb_load_Cards_chunks.dump" INTO TABLE vcc2.tmp_cards CHARACTER SET latin1
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;

如何在登录mysql时对目录中的每个文件执行此操作?

envsm3lx

envsm3lx1#

尝试:
文件: load_csv.sh (-r-x------ user user load_csv.sh*) ```

!/bin/bash

for current_csv in *.csv
do
mysql --login-path=myconnection -e "USE test" -e "
LOAD DATA LOCAL INFILE '$current_csv'
INTO TABLE temp_table
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(DATE, TIME);"
done

请参阅4.6.6 mysql\u config\u editor-mysql配置实用程序。
文件: `0.csv` ```
DATE,TIME
"2000-01-01","00:00:00"
"2001-01-01","12:00:00"
"2002-01-01","23:00:00"

文件: 1.csv ```
DATE,TIME
"2003-01-01","23:00:00"
"2004-01-01","00:00:00"
"2005-01-01","12:00:00"

文件: `2.csv` ```
DATE,TIME
"2006-01-01","12:00:00"
"2007-01-01","23:00:00"
"2008-01-01","00:00:00"

mysql命令行:

mysql> CREATE DATABASE IF NOT EXISTS `test`;
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> USE `test`;
Database changed

mysql> DROP TABLE IF EXISTS `temp_table`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `temp_table` (
    ->   `id` SERIAL,
    ->   `DATE` DATE,
    ->   `TIME` TIME
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> \! bash
$ ./load_csv.sh
$ exit
exit

mysql> SELECT `id`, `DATE`, `TIME`
    -> FROM `temp_table`;
+----+------------+----------+
| id | DATE       | TIME     |
+----+------------+----------+
|  1 | 2000-01-01 | 00:00:00 |
|  2 | 2001-01-01 | 12:00:00 |
|  3 | 2002-01-01 | 23:00:00 |
|  4 | 2003-01-01 | 23:00:00 |
|  5 | 2004-01-01 | 00:00:00 |
|  6 | 2005-01-01 | 12:00:00 |
|  7 | 2006-01-01 | 12:00:00 |
|  8 | 2007-01-01 | 23:00:00 |
|  9 | 2008-01-01 | 00:00:00 |
+----+------------+----------+
9 rows in set (0.00 sec)

相关问题