错误在C#LOAD DATA INFILE查询
问题描述:
我有下面的代码的问题: -错误在C#LOAD DATA INFILE查询
private void btnUpload_Click(object sender, EventArgs e)
{
string nm = txtFilename.Text;
string qry = "LOAD DATA INFILE 'D:\\HHTFiles\\" + nm + "' INTO TABLE `table1`.`location`FIELDS TERMINATED BY '-->'LINES TERMINATED BY '\r\n'(Barcode,BinLoc);";
cmd = new OdbcCommand(qry, con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show(" File loaded successfully...");
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledailog1 = new OpenFileDialog();
openfiledailog1.InitialDirectory = "D:\\HHTFiles\\";
openfiledailog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openfiledailog1.FilterIndex = 2;
openfiledailog1.RestoreDirectory = true;
if (openfiledailog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((openfiledailog1.OpenFile()) != null)
{
txtFilename.Text = openfiledailog1.SafeFileName.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
它运行正常,如果我给完整的文件路径在我的查询,如: - 字符串QRY =“ LOAD DATA INFILE'D:\ HHTFiles \ ABC.txt'INTO TABLE table1
。location
FIELDS TERMINATED BY' - >'LINES TERMINATED BY'\ r \ n'(Barcode,BinLoc);“; 但是,当文件路径传递给String变量时,它会引发错误。
错误: - ERROR [HY000] [MySQL的] [ODBC 5.1驱动]的[mysqld-48年5月1日社区]文件 'd:HHTFilesABC.txt' 未找到(ERRCODE:2)
答
尝试Path.Combine
Path.Combine("D:\\HHTFiles\\", nm);
而且为了使用StringBuilder来构建查询
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("LOAD DATA INFILE ");
stringBuilder.Append(Path.Combine("D:\\HHTFiles\\", nm));
stringBuilder.Append(" INTO TABLE table1.location");
stringBuilder.Append(" FIELDS TERMINATED BY '-->'");
stringBuilder.Append(" LINES TERMINATED BY (");
stringBuilder.Append(Barcode.BinLoc);
stringBuilder.Append(")");
string qry = stringBuilder.ToString();
答
@Aghilas它得到解决:)虽然我不知道为什么,我在第一时间得到错误。 Anway,我用'/'替换了'\',并且运行良好。
string nm = txtFilename.Text;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("LOAD DATA INFILE ");
stringBuilder.Append(Path.Combine("'D:/HHTFiles/", nm));
stringBuilder.Append("' INTO TABLE `table1`.`location`FIELDS TERMINATED BY '-->'LINES TERMINATED BY '\r\n'(Barcode,BinLoc);");
感谢您的快速回复。我试过你的代码,但我仍然得到了以前的错误。错误[HY000] [MySQL] [ODBC 5.1驱动程序] [mysqld-5.1.48-community]找不到文件'D:HHTFilesABC.txt'(Errcode:2) – RookieCoder 2012-07-25 12:26:19
高兴地回复你,验证D:HHTFiles/ABC。 txt存在路径 – 2012-07-25 12:30:50
是的,ABC.txt文件存在于指定的路径中。我甚至在上面的代码段上应用了断点。它显示qry =“LOAD DATA INFILE'D:\\ HHTFiles \\ ABC.txt'INTO TABLE 'table1'.'location'FIELDS TERMINATED BY' - >'LINES TERMINATED BY'\ r \ n'(Barcode,BinLoc);“。如果我在Mysql Editor上运行这个查询,它运行正常并且1行受到影响。但相同的查询不在C#中工作。我很困惑... – RookieCoder 2012-07-26 05:56:04