将数据从文本文件导入MySQL中的特定列

时间:2012-08-29 04:45:41

标签: mysql

我有一个名为system_settings的表,其中有3列,即IDActual_Setting& Standards_Setting

ID列中有3行,即'Virtual Machine 1''Virtual Machine 2'& 'Virtual Machine 3'

我希望将文本文件中的数据导入'Actual_Setting'ID = 'Virtual Machine 1'

我尝试过使用此查询:

LOAD DATA LOCAL IN FILE 'C:/Program Files/MySQL/MySQL Server 5.5/bin/syspolicy.txt'
INTO system_settings(Actual_Setting)
WHERE ID LIKE 'Virtual Machine 1';

但它会返回错误。

我使用MySQL Server 5.5,MySQL Query Browser& Windows 7 PC。

1 个答案:

答案 0 :(得分:0)

LOAD DATA将始终将数据插入行,而不是更新现有行。

但是,如果发生密钥冲突,它可以先使用REPLACE关键字删除现有行。如果UNIQUE列上有ID个密钥,并且您不需要保留Standards_Setting的值,则可以利用此功能:

LOAD DATA LOCAL INFILE 'C:/Program Files/MySQL/MySQL Server 5.5/bin/syspolicy.txt'
  REPLACE INTO TABLE system_settings
  FIELDS TERMINATED BY '' ENCLOSED BY '' ESCAPED BY ''
  LINES STARTING BY '' TERMINATED BY ''
  (Actual_Setting)
  SET ID = 'Virtual Machine 1'

(请注意,由于您要将整个文件读入单个字段,因此必须覆盖默认值并明确指定没有字段或行终止/引用/转义字符。)

否则,如果您需要更新现有记录,我建议您将文件加载到临时表中,然后使用内容更新您的表:

CREATE TEMPORARY TABLE foo (content LONGTEXT);

LOAD DATA LOCAL INFILE 'C:/Program Files/MySQL/MySQL Server 5.5/bin/syspolicy.txt'
  INTO TABLE foo
  FIELDS TERMINATED BY '' ENCLOSED BY '' ESCAPED BY ''
  LINES STARTING BY '' TERMINATED BY ''
  (content);

UPDATE system_settings
  SET Actual_Setting = (SELECT content FROM foo)
WHERE ID = 'Virtual Machine 1';

DROP TEMPORARY TABLE foo;