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

时间:2018-06-12 12:17:26

标签: 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'列中的所有条目都是空的或整数。

1 个答案:

答案 0 :(得分:0)

您可以使用 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)