对不起我的英语..
我编写了一个 shell 脚本来通过 csv 文件更新本地 mysql 数据库中的表。
#! /bin/sh
mysql --user=root --password=12345 \
-e "USE database one;" \
-e "CREATE TABLE IF NOT EXISTS xxxx LIKE xxx;" \
-e "TRUNCATE TABLE xxxx;" \
-e "LOAD DATA INFILE \"/var/lib/mysql-files/data.csv\" INTO TABLE xxxx FIELDS TERMINATED BY ';' ;" \
CSV 文件:
1;Müller;Max
2;Wayne;Roney
我的数据库“id”中的字段是整数和主键。 如果我在 csv 中更改此字段,例如
a;Müller;Max
2;Wayne;Roney
脚本将 csv 格式的数据加载到表中。 我希望出现错误,因为 csv 不正确。
我必须做什么?
谢谢!
最佳答案
如果您尝试将像“a”这样的字符串插入到整数列中,它会自动转换为数值。 'a' 的数值为 0,因为它没有前导数字。
我找到了一种在这种情况下强制出错的方法。
首先,您的 id 列不得使用 AUTO_INCRMENT
。这将允许 0,因为它会导致生成新的 id。
其次,在加载数据之前,您必须预先插入主键值为 0
的行。然后,如果像 'a'
这样的值转换为 0,则会导致 UNIQUE KEY 违规。
mysql --user=root --password=12345 \
-e "USE database one;" \
-e "CREATE TABLE IF NOT EXISTS xxxx LIKE xxx;" \
-e "TRUNCATE TABLE xxxx;" \
-e "INSERT INTO xxxx (id) VALUES (0);" \
-e "LOAD DATA INFILE \"/var/lib/mysql-files/data.csv\" INTO TABLE xxxx FIELDS TERMINATED BY ';' ;" \
-e "DELETE FROM xxxx WHERE id = 0;"
请注意,如果您使用LOAD DATA LOCAL INFILE...
,这将不起作用
https://dev.mysql.com/doc/refman/5.7/en/load-data.html
Without LOCAL, an error occurs when a duplicate key value is found, and the rest of the text file is ignored. With LOCAL, the default behavior is the same as if IGNORE is specified; this is because the server has no way to stop transmission of the file in the middle of the operation.
如果这些条件不适合您,那么您必须在脚本中编写一些额外的代码来检查 csv 文件,并修复错误数据,或者打印错误并退出。
关于mysql - 加载数据文件 - 上传 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48625872/