我有以下代码来读取CSV文件并填充DataTable:
string sql = @"SELECT * FROM [" + fileName + "]";
using (OleDbConnection connection = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
}
这段剪辑效果很好,但代码分析却抱怨它(CA2100)。我应该更改构建查询字符串的方式,以便我可以使用参数。
我正在尝试解决此问题,但似乎通常的OleDbParameter用法不起作用。查询是使用参数名称而不是其值构建的:
string sql = @"SELECT * FROM @param";
using (OleDbConnection connection = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
command.Parameters.Add(new OleDbParameter("@param", fileName));
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
}
有什么想法吗?