问题
I have an Excel file and I want update multiple rows in a sheet.So I write this code :
OleDbConnection cn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + serverPath + ";Extended Properties = Excel 8.0;");
try
{
strUpd = "";
strUpd += "update [Data14City$] set B_1_1 = 5 ,B_1_2 = 26 ,B_1_3 = 44 ,B_1_4 = 8 where id = 1 ";
strUpd += " update [Data14City$] set B_1_1 = 0 ,B_1_2 = 8 ,B_1_3 = 17 ,B_1_4 = 0 where id = 2";
cn.Open();
OleDbCommand cmdInsert = new OleDbCommand(strUpd, cn);
cmdInsert.ExecuteNonQuery();
cn.Close();
}
catch
{
}
and I got this error:
Syntax error (missing operator) in query expression 'id = 1 update [Data14City$] set B_1_1 = 0 ,B_1_2 = 8 ,B_1_3 = 17 ,B_1_4 = 0 where id = 2'.
and I when I add ;
to this line :
strUpd += "update [Data14City$] set B_1_1 = 5 ,B_1_2 = 26 ,B_1_3 = 44 ,B_1_4 = 8 where id = 1;";
I got this error:
Characters found after end of SQL statement.
how I can execute multiple statement in Excel?
thanks
回答1:
You don't really need to stack up your updates like that (in fact, as has been pointed out above, you can't). It doesn't take much longer to execute them individually. Here's the code I've been using and it works fine (I actually have mine in a loop, but it'll work equally well if you can't loop your updates).
cn.Open();
using (OleDbCommand cmd = cn.CreateCommand())
{
cmd.CommandText = "update [Data14City$] set B_1_1 = 5 ,B_1_2 = 26 ,B_1_3 = 44 ,B_1_4 = 8 where id = 1";
cmd.ExecuteNonQuery();
cmd.CommandText = "update [Data14City$] set B_1_1 = 0 ,B_1_2 = 8 ,B_1_3 = 17 ,B_1_4 = 0 where id = 2";
cmd.ExecuteNonQuery();
// ... and so on
}
cn.Close();
来源:https://stackoverflow.com/questions/13359748/execute-multiple-update-command-on-excel