0

以下代码似乎有问题我想使用以下代码片段在数据库中插入一个值。

DataTable dtUsers = new DataTable("tblUsers");
BindingSource bsUsers = new BindingSource();
SqlDataAdapter daUsers = new SqlDataAdapter("usp_GetUsers", Properties.Resources.ConnectionString);


     daUsers.InsertCommand = new SqlCommand("usp_InsertNewUser");
                daUsers.InsertCommand.Connection = new SqlConnection(Properties.Resources.ConnectionString);
                daUsers.InsertCommand.CommandType = CommandType.StoredProcedure;
                daUsers.InsertCommand.Parameters.Clear();
                daUsers.InsertCommand.Parameters.Add("@username", SqlDbType.VarChar, 50).Value = txtUser.Text;
                daUsers.InsertCommand.Parameters.Add("@password", SqlDbType.VarChar, 50).Value = txtPass.Text;
                daUsers.InsertCommand.Parameters.Add("@userType", SqlDbType.Int).Value = cbxUserType.SelectedValue;
                daUsers.Update(dtUsers);

在你问之前,存储过程工作正常。而且,如果我将上面的 InsertCommand 更改为 SelectCommand 并调用 Fill 方法,那么一切正常!这件事令人沮丧,因为如果您使用 Select/Fill 组合,数据适配器的插入/更新方法无法正常工作。没有数据行被插入,因为我也监控了这一点。也不会产生异常。铝

4

2 回答 2

2

With that exact code snippet, nothing will be inserted - the way SqlDataAdapter.Update() works is for every DataRow in the supplied datatable (dtUsers) that has a RowState of Added, it will call the InsertCommand that has been defined on the data adapter. Likewise, for every DataRow with a RowState of Modified, it will call the UpdateCommand that has been defined (if there is one).

The purpose of SqlDataAdapter.Update(), is to be supplied with a DataTable (potentially containing new, updated and deleted rows) which it will call the appropriate defined sproc for.

So in your code, you have nothing in dtUsers with a RowState of Added and so there is no work to send to the DB....hence nothing gets inserted.

于 2011-03-30T15:44:32.153 回答
-1

您可以adapter.InsertCommand.ExecuteNonQuery()在设置参数以提交插入数据库后使用。

例如:

DataTable dtUsers = new DataTable("tblUsers");
BindingSource bsUsers = new BindingSource();
SqlDataAdapter daUsers = new SqlDataAdapter("usp_GetUsers",Properties.Resources.ConnectionString);
daUsers.InsertCommand = new SqlCommand("usp_InsertNewUser");
daUsers.InsertCommand.Connection = new SqlConnection(Properties.Resources.ConnectionString);
daUsers.InsertCommand.CommandType = CommandType.StoredProcedure;
daUsers.InsertCommand.Parameters.Clear();
daUsers.InsertCommand.Parameters.Add("@username", SqlDbType.VarChar, 50).Value = txtUser.Text;
daUsers.InsertCommand.Parameters.Add("@password", SqlDbType.VarChar, 50).Value = txtPass.Text;
daUsers.InsertCommand.Parameters.Add("@userType", SqlDbType.Int).Value = cbxUserType.SelectedValue;
daUsers.InsertCommand.ExecuteNonQuery();
daUsers.Update(dtUsers);
于 2016-05-22T17:47:36.843 回答