execute multiple update command on Excel

隐身守侯 提交于 2019-12-07 03:30:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!