SQL / PHP创建数据库并加载.CSV

时间:2014-08-23 23:01:28

标签: php mysql sql csv bulkinsert

到目前为止,我已经删除了所有表并创建了数据库,这是有效的。但是当我尝试创建一个新表并加载.csv文件时,它将无法工作。

mysql_select_db($dbName, $dbConnection);
$sql = "CREATE TABLE ".$dbTable." (ID int(6) auto_increment NOT NULL, Username varchar(20) NOT NULL, Password varchar(20) NOT NULL, UserType int(1) NOT NULL, FirstName varchar(15) NOT NULL, LastName varchar(15) NOT NULL, DOB DATETIME NOT NULL, Phone varchar(15) NOT NULL, Department varchar(15),PRIMARY KEY(ID))";
if(mysql_query($sql, $dbConnection))
{
    echo("Table '".$dbTable."' created<br />");
}
else
{
    echo("Error creating table '".$dbTable."': ".mysql_error()."<br />");
}

$sql = "LOAD DATA INFILE 'users.csv' INTO ".$dbTable." FIELDS TERMINATED BY ',' (ID, Username, Password, UserType, FirstName, LastName, DOB, Phone, Department)";
if(mysql_query($sql, $dbConnection))
{
    echo("Added records to '".$dbTable."' table<br />");
}
else
{
    echo("Error inserting records into '".$dbTable."': ".mysql_error()."<br />");
}

2 个答案:

答案 0 :(得分:0)

你可以试试这个。我希望它能起作用

    LOAD DATA INFILE '<filePath>' 
    INTO TABLE <tableName> 
    FIELDS TERMINATED BY ',' 
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
    IGNORE 1 ROWS
    (ID, Username, Password, UserType, FirstName, LastName, DOB, Phone, Department);

答案 1 :(得分:0)

更具体地说明错误,尝试输出

 mysql_error();
在错误处理中

并确保.csv文件路径正确。或者进入mysql错误日志并发出:

 tailf /mysql.log or tail -f /mysql.log