0

我已经搜索了几个小时,但它不起作用。

我有一个 csv 总统文件。第一行是标题。

Presidency ,President ,Wikipedia Entry,Took office ,Left office ,Party ,Portrait,Thumbnail,Home State

我想创建一个只有Presidency,President和的关系Party

$sqlquerycreate1 = "CREATE TABLE IF NOT EXISTS `sample1` (
  `Presidency`  VARCHAR(30),
  `President` VARCHAR(30),
  `Party` VARCHAR(30)
)";
mysql_query($sqlquerycreate1);

# download the file off the internet
$file = file_get_contents("http://localhost/sample.csv");
$filepath = "sample.csv";
file_put_contents($filepath, $file);

# load the data into nycgrid table
$pt11 = "LOAD DATA LOCAL INFILE ";
$pt21 = "'C:/xampp/htdocs/test/file/sample.csv' INTO TABLE sample1(Presidency,President,@Wikipedia Entry,@Took office ,@Left office ,Party,@Portrait,@Thumbnail,@Home State) ";
$pt31 = "FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ";
$pt41 = "LINES TERMINATED BY '\r\n' ";
$pt51 = "IGNORE 1 LINES";
$sqlquerynew1 = $pt11.$pt21.$pt31.$pt41.$pt51;
mysql_query($sqlquerynew1);

它不起作用。表已创建,但未加载数据。知道为什么吗?谢谢。


mysql> LOAD DATA LOCAL INFILE 'C:/xampp/htdocs/sample.csv' INTO TABLE sample1(Pr
esidency, President, @x, @x, @x, Party, @x, @x, @x) FIELDS TERMINATED BY ',' ENC
LOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES;


ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'FIELD
S TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINE' at
line 1
4

1 回答 1

5

您的LOAD DATA语句中有语法错误。尤其是:

  1. 手册所述:

    用户变量写为@var_name,其中变量名称var_name由字母数字字符、“<code>.”、“<code>_”和“<code>$”组成。如果您将用户变量名称作为字符串或标识符引用(例如,、、或),则用户变量名称可以@'my-var'包含@"my-var"其他@`my-var`字符

    因此,您的名为@Wikipedia Entry,和的变量在语法上都是不正确的。您必须删除空格或引用变量名。@Took office@Left office@Home state

    但是,除非您打算在别处引用它们,否则您不需要使用不同的变量名称。如手册所述:

    您还可以通过将输入值分配给用户变量而不将变量分配给表列来丢弃输入值:

    LOAD DATA INFILE 'file.txt'
      INTO TABLE t1
      (column1, @dummy, column2, @dummy, column3);
    
  2. ,FIELDS和子句都应该LINES列表之前。如手册中所述,语法为:IGNORE

    LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'
        [REPLACE | IGNORE]
        INTO TABLE tbl_name
        [CHARACTER SET charset_name]
        [{FIELDS | COLUMNS}
            [TERMINATED BY 'string']
            [[OPTIONALLY] ENCLOSED BY 'char']
            [ESCAPED BY 'char']
        ]
        [LINES
            [STARTING BY 'string']
            [TERMINATED BY 'string']
        ]
        [IGNORE number LINES]
        [(col_name_or_user_var,...)]
        [SET col_name = expr,...]

因此,您可以简单地执行以下操作:

LOAD DATA LOCAL INFILE 'C:/xampp/htdocs/test/file/sample.csv'
    INTO TABLE sample1
    FIELDS
        TERMINATED BY ','
        ENCLOSED BY '\"'
    LINES
        TERMINATED BY '\r\n'
    IGNORE 1 LINES
    (Presidency, President, @x, @x, @x, Party, @x, @x, @x)
于 2012-05-20T09:29:16.397 回答