我正在将Excel文件(仅约1000条记录)导入到专用的SQL Server数据库。因为我需要处理来自Excel的传入数据(每行添加一个GUID,进行一些数据转换),我希望逐行执行并且不想批量导入(尽管我对交易没有任何反应)。将Excel文件逐行导入到SQL Server
我很困惑如何正确地做到这一点。我可以用一个SQLCommand
与参数,像这样:
SqlCommand sqlCommand = new SqlCommand("insert into TestTable(GUID,Name,Pricing) values(@GUID,@Name,@Pricing)", sqlConn);
foreach (DataRow dr in ds.Tables[0].Rows) //<-- this is my Excel file to iterate through
{
sqlCommander.Parameters.Clear();
String refGUID = Guid.NewGuid().ToString();
sqlCommander.Parameters.AddWithValue("GUID", refGUID);
sqlCommander.Parameters.AddWithValue("Name", dr.ItemArray[0]);
sqlCommander.Parameters.AddWithValue("Pricing", dr.ItemArray[1]);
sqlCommander.ExecuteNonQuery();
}
或者,我可以使用“连接”模式,像这样:
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT GUID, Name, Pricing FROM TestTable", sqlConn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet myDataSet = new DataSet();
dataAdapter.Fill(myDataSet, "TestTable");
foreach (DataRow dr in ds.Tables[0].Rows) //<-- this is my Excel file to iterate through
{
DataRow row = myDataSet.Tables[0].NewRow();
row["GUID"] = refGUID;
row["Name"] = dr.ItemArray[0];
row["Pricing"] = dr.ItemArray[1];
myDataSet.Tables[0].Rows.Add(row);
dataAdapter.Update(myDataSet);
}
现在我的问题有以下几点:
- 为每一行发送
INSERT
命令(这将是SqlCommand
方法)还是更好地填充特殊DataSet
(第二种方法)?我猜这对于有1000个插入SQL服务器是相当“愚蠢的”? dataAdapter.Update(myDataSet)
< - 我应该在迭代所有Excel行或每行(如上面的示例代码所示)后执行该操作,这是否会奇迹般地创建事务?- 我应该使用哪种方法?还有LINQ to SQL - 为什么不使用它(性能可能是因为另一层)?
DataSet
当读取Excel文件时发生某些错误时会发生什么 - 更新仍然推送到SQL服务器还是一切丢失?
简而言之:我想导入Excel文件到SQL Server行由行而制作上的数据变化要导入(我不希望使用SSIS包[因为除了数据转换之外,我对Excel文件做了很多工作,例如将其导入Sharepoint并解雇工作流]或BizTalk)
» »如何做到这一点?
最后我继续购买 Aspose Cells。 Aspose拥有一套非常优秀的工具。
为什么你不想使用SSIS?如果该工具适合... – 2010-10-27 14:43:46
因为我同时将Excel文件导入Sharepoint,并创建Infopath表单和任务并启动工作流程,所以不是简单地导入。与使用一些SSIS包(除了基本示例之外,我从来没有创建过这个包)相比,我更愿意“掌握代码”。 – 2010-10-27 14:54:54
你的问题忽略提及新的信息....但它几乎肯定可能在SSIS ... – 2010-10-27 15:02:43