mysql - 尝试将 csv 文件导入 MySQL 表时总是出错

标签 mysql import

我正在尝试将一个 csv 文件导入到我的数据库表中。 csv 文件的前两行是:

Nr$Name$Telefon$Flaeche$Einwohner$Pendler    
1$Innenstadt$069 755 10100$2.11$10100$   

我尝试导入的表(“polizeireviere”)是这样的:

+-----------+---------------+------+-----+---------+-------+     
| Field     | Type          | Null | Key | Default | Extra |     
+-----------+---------------+------+-----+---------+-------+      
| Nr        | int(5)        | YES  |     | NULL    |       |      
| Name      | varchar(20)   | YES  |     | NULL    |       |     
| Telefon   | varchar(34)   | YES  |     | NULL    |       |    
| Flaeche   | decimal(10,0) | YES  |     | NULL    |       |     
| Einwohner | int(10)       | YES  |     | NULL    |       |     
| Pendler   | int(10)       | YES  |     | NULL    |       |     
+-----------+---------------+------+-----+---------+-------+      

我的导入命令是这些:

load data infile 'polizeireviere.csv'    
into table polizeireviere     
fields terminated by '$'    
lines terminated by '\n'    
ignore 1 lines;    

但是我得到了这个错误:

' for column 'Pendler' at row 1nteger value: ' 

但我不知道那是什么意思,因为“Pendler”列中的所有条目都是空的或整数。

最佳答案

您可以使用 SET 子句解决此问题,如下所示:

你的加载命令应该是这样的:

load data infile '/var/lib/mysql-files/vivek/test.dat' 
into table polizeireviere
fields terminated by '$'
lines terminated by '\n'
ignore 1 rows
(Nr,Name,Telefon,Flaeche,Einwohner,@Pendler)
SET Pendler = IF(@Pendler='',null,@Pendler);

示例:

mysql> CREATE TABLE polizeireviere (
    ->   Nr int(5) DEFAULT NULL,
    ->   Name varchar(20) DEFAULT NULL,
    ->   Telefon varchar(34) DEFAULT NULL,
    ->   Flaeche decimal(10,0) DEFAULT NULL,
    ->   Einwohner int(10) DEFAULT NULL,
    ->   Pendler int(10) DEFAULT NULL
    -> );
Query OK, 0 rows affected (0.46 sec)

mysql> 
mysql> load data infile '/var/lib/mysql-files/vivek/test.dat' 
    -> into table polizeireviere
    -> fields terminated by '$'
    -> lines terminated by '\n'
    -> ignore 1 rows
    -> (Nr,Name,Telefon,Flaeche,Einwohner,@Pendler)
    -> SET Pendler = IF(@Pendler='',null,@Pendler);
Query OK, 1 row affected, 1 warning (0.04 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 1

mysql> select * from polizeireviere;
+------+------------+---------------+---------+-----------+---------+
| Nr   | Name       | Telefon       | Flaeche | Einwohner | Pendler |
+------+------------+---------------+---------+-----------+---------+
|    1 | Innenstadt | 069 755 10100 |       2 |     10100 |    NULL |
+------+------------+---------------+---------+-----------+---------+
1 row in set (0.00 sec)

关于mysql - 尝试将 csv 文件导入 MySQL 表时总是出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50817022/

相关文章:

php - 单个html表单插入到具有一对多关系的多个mysql表中

mysql - 如何将这两个查询合并为一个。?

mysql - 合并 2 个 mysql 表的查询

Python:强制导入更喜欢 .py 而不是 .so

php - MySQL 查询使用 $_GET

Mysql查询计算跳出率

objective-c - Objective C 中的循环 #import/@class 问题

node.js - 结束后写入错误

模块中的 python 导入类抛出 ImportError

android - 将完整的机器人应用程序移植到黑莓手机上需要进行哪些转换工作?