目前我正在尝试使用此功能导入 CSV 文件:
public DataSet ImportCommaSeparatedValueFileToDataSet(string SourceFile)
{
var dsImportCSVtoDataSetReturn = new DataSet();
using (var objAdapter1 = new OleDbDataAdapter())
{
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + SourceFile.Substring(0, SourceFile.LastIndexOf(@"\")) + ";Extended Properties='text;HDR=Yes;FMT=Delimited'";
var objConnection = new OleDbConnection(sConnectionString);
objConnection.Open();
var objCmdSelect = new OleDbCommand("SELECT * FROM " + SourceFile, objConnection);
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(dsImportCSVtoDataSetReturn);
objConnection.Close();
}
return dsImportCSVtoDataSetReturn;
}
当我尝试导入文件名中没有空格的文件时,它工作正常。当我尝试导入以下文件时:
D:\Workspace\WoldCard export.csv
然后我收到以下异常:
excException = {"Syntax error in FROM clause."}
Source = "Microsoft JET Database Engine"
StackTrace " at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)\r\n at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)\r\n at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)\r\n at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)\r\n at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)\r\n at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.OleDb.OleDbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)\r\n at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)\r\n at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)\r\n at CommonObjects4.clsUtilityOffice.ImportCommaSeparatedValueFileToDataSet(String SourceFile) in D:\\DevProjects\\CommonObjects4\\classes\\clsUtilityOffice.cs:line 262" string
因此,问题似乎很明显,问题在于 SQL 子句中的文件名中有空格;但是,当我尝试使用单引号来解决问题时:
var objCmdSelect = new OleDbCommand("SELECT * FROM '" + SourceFile + "'", objConnection);
然后我收到这个异常:
excException = {"''D:\Workspace\WoldCard export.csv'' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long."}
另外,当我尝试使用参数时:
var objCmdSelect = new OleDbCommand("SELECT * FROM @SourceFile", objConnection);
objCmdSelect.Parameters.Add("@SourceFile", SqlDbType.NVarChar).Value = SourceFile;
然后我收到这个异常:
excException = {"Syntax error in query. Incomplete query clause."}
另外,我后来从http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/1c399bf7-a6b3-47bb-8897-d4247b4938f0了解到表名不能是参数。有没有人有什么建议?TIA。