English 中文(简体)
如何使用存储程序进行更新通讯命令文本?
原标题:How to use stored procedure for the CommandText of UpdateCommand?
  • 时间:2012-05-24 19:42:41
  •  标签:
  • c#
  • ado.net

我有一个用于编辑表格的 DataGridView 。 以下代码用于更新表格 。

using (SqlConnection con = new SqlConnection("...."))
{
    con.Open();

    SqlDataAdapter da = new SqlDataAdapter("select * from T", con);
    SqlCommandBuilder cb = new SqlCommandBuilder(da);
    cb.ConflictOption = ConflictOption.OverwriteChanges;

    da.UpdateCommand = cb.GetUpdateCommand();
    // da.UpdateCommand.CommandText = "exec sp1 @p1, @p2, @p3...";
    da.InsertCommand = cb.GetInsertCommand();
    da.DeleteCommand = cb.GetDeleteCommand();
    da.Update(datatable.GetChanges());
}

我发现 da. update( 数据表. GetCchanges ()) 根据修改后的栏目, 智能生成了最起码的设定条款 。

update T set c1 = @p1 where K = @p2 -- If only c1 is changed in the grid 
update T set c1 = @p1, c2 = @p2 where K = @p3 -- if both c1 and c2 is changed
update T set c4 = @p1 where K = @p2 -- if only c4 is changed
......

如何写入 CommandText 的存储程序?

问题回答

您会想要在服务器上创建一个接收参数的存储程序。 您正在使用的方法是生成 SQL, 不使用存储程序, 它会将连接发送到服务器 。 如果我命名了 sproc UnitedSUser Table :

oleDbCommand1.CommandText = "UpdateSomeUserTable";
oleDbCommand1.CommandType = System.Data.CommandType.StoredProcedure;

oleDbCommand1.Parameters["us_id"].Value = "668987";
oleDbCommand1.Parameters["us_lname"].Value = "White";
oleDbCommand1.Parameters["us_fname"].Value = "Johnson";

oleDbConnection1.Open();
oleDbCommand1.ExecuteNonQuery();
oleDbConnection1.Close();

这是一个代码的嗅觉, 我不建议使用, 但它的工作原理。

dataAdapter.RowUpdating +=  (sender, e) =>
{
    if (e.Command != null && !string.IsNullOrEmpty(e.Command.CommandText))
    {
       e.Command.CommandText = $"";                                
    }
};




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签