问题
I just switched to Webmatrix because the server I was using stopped supporting MySQL / PHP. Now I'm converting my old php mysql site to Webmatrix with SQL Server Compact. But I have hit a little snag. I'm using a script to directly import csv files into my database, in php/mysql this was not that hard to do but I can't get it to work in Webmatrix and SQL Server Compact. Anyone having ideas on why it does not work?
mysql_query("TRUNCATE TABLE `tmp_st_age`");
$age = 'load data local infile "../csv/tmp_st_age.csv"
into table `tmp_st_age`
fields terminated by ";"
enclosed by "\""
LINES TERMINATED BY "\r\n"
IGNORE 1 LINES';
mysql_query($age) or die(myqsl_error());
echo "Done! ".mysql_affected_rows()." rows inserted into tmp_st_age.<br>";
Above code is something I'm trying to implement in Webmatrix but I can't seem to get it correct. Is it so that this is a mysql feature only? If so, is there any good workaround that means not using a third party program, a web based input is what I'm looking for.
回答1:
If you were using SQL Server instead of SQL Compact, you could use BULK INSERT which is a very similar approach to the MySQL one you illustrated in your question. Unfortunately SQL Compact doesn't support that so you are left with reading the csv and inserting each row individually. Something along the lines of:
var db = Database.Open("your_db");
var data = File.ReadAllLines(path_to_csv_file);
foreach(var row in data){
var columns = row.Split(new []{';'});
var sql = "INSERT INTO MyTable (f1, f2, f3, etc) VALUES (@0, @1, @2, etc)";
db.Execute(sql, item[0], item[1], item[2], etc);
}
来源:https://stackoverflow.com/questions/20594114/webmatrix-csv-import-to-sql-server-compact