我正在尝试将CSV文件放入MySQL表中,请参阅此主题:
Loading CSV into MySQL Is This a Bug? - File Not Found Exception
我已经发现执行命令会抛出异常,因为文件名中存在双重反冲。如果我将CSV文件移动到可执行文件所在的位置并且仅提供文件名,则它运行正常。问题是LOAD DATA语句只接受文件名的字符串,根据MySQL文档。我无法传递参数,我不知道在C#中如何在字符串中指定'\'而不首先转义它。我正在使用String.Format()来构建命令字符串。我已经尝试了String.Format(@“”)和没有@,两者都没有工作。有没有人有建议?我搜索了论坛,找到了一个PHP的例子,想知道C#是否有什么东西。
这是我现在的代码,其中InputFileListView是用户选择加载到数据库中的文件列表。问题是任何ToString()方法访问文件路径信息,把\放在字符串中。这会导致执行命令
的问题IEnumerable<FileInfo> files = this.InputFileListView.Items.Cast<FileInfo>();
// just using the first entry in InputFileListView for now
string working = String.Format("LOAD DATA LOCAL INFILE '{0}' IGNORE", files.FirstOrDefault().ToString()) +
String.Format("INTO TABLE {0} COLUMNS TERMINATED BY ',' LINES TERMINATED BY '\n'", "by_switch")+
String.Format("IGNORE 1 LINES (`Switch`,`Port`,`WWPN`,@the_slot,`Port Index`,@the_time,`Interval`,`Port Send Packet Rate`,")+
String.Format("`Port Receive Packet Rate`,`Total Port Packet Rate`,`Port Send Data Rate`,")+
String.Format("`Port Receive Data Rate`,`Total Port Data Rate`,`Port Peak Send Data Rate`,`Port Peak Receive Data Rate`,")+
String.Format("`Port Send Packet Size`,`Port Receive Packet Size`,`Overall Port Packet Size`,`Error Frame Rate`,")+
String.Format("`Dumped Frame Rate`,`Link Failure Rate`,`Loss of Sync Rate`,`Loss of Signal Rate`,`CRC Error Rate`,")+
String.Format(" `Short Frame Rate`,`Long Frame Rate`,`Encoding Disparity Error Rate`,")+
String.Format("`Discarded Class3 Frame Rate`,`F-BSY Frame Rate`,`F-RJT Frame Rate`, `Port Send Bandwidth Percentage`,")+
String.Format("`Port Receive Bandwidth Percentage`, Overall Port Bandwidth Percentage`,`Primitive Sequence Protocol Error Rate`,")+
String.Format("`Invalid Transmission Word Rate`,`Link Reset Transmitted Rate`,`Link Reset Received Rate`)")+
String.Format("SET Slot = nullif(@the_slot,''),")+
String.Format(@"Time= str_to_date(@the_time,'%m/%d/%y %h:%i %p')");
我试过这个,它没用。
string tester = files.FirstOrDefault().Directory.ToString();
tester = tester.Replace(@"\\", @"\");
答案 0 :(得分:0)
我没有找到问题的答案,但我找到了解决方法。我想做什么使用BulkLoader:
var bl = new MySqlBulkLoader(sqlconnect);
bl.TableName = "by_switch";
bl.FieldTerminator = ",";
bl.LineTerminator = "\n";
bl.FileName = files.FirstOrDefault().ToString();
bl.NumberOfLinesToSkip = 1;
int inserted = bl.Load();