我有以下代码,并没有将记录更新到数据库。
SqlDataAdapter da = new SqlDataAdapter("spInvent",cs);
da.UpdateCommand.CommandType = System.Data.CommandType.StoredProcedure;
da.UpdateCommand.Parameters.AddWithValue("@DisplayNo", displayNo);
da.UpdateCommand.Parameters.AddWithValue("@Q", Q);
da.UpdateCommand.ExecuteNonQuery();
DataSet ds = new DataSet();
da.Fill(ds);
gvInfo.DataSource = ds;
gvInfo.DataBind();
我收到错误:
da.UpdateCommand.CommandType = System.Data.CommandType.StoredProcedure;
答案 0 :(得分:4)
正确的语法是:
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
SqlConnection cs = new
SqlConnection(ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
if (cs.State == ConnectionState.Closed) {
cs.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = cs;
cmd.CommandText = "UpdateStoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DisplayNo", displayNo);
cmd.Parameters.AddWithValue("@Q", Q);
int result = cmd.ExecuteNonQuery();
if (result > 0) {
//Your Database is updated. To show it in gridview, you have
//to select the table and show its data.
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = cs;
cmd1.CommandText = "SelectStoredProcedureName";
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("@displayId", 0);
//In the SelectStoredProcedure, use @displayId = 0 to
//show all rows.
SqlDataAdapter adpt = new SqlDataAdapter();
adpt.SelectCommand = cmd1;
DataSet ds = new DataSet();
adpt.Fill(ds);
cs.Close();
GridViewID.DataSource = ds;
GridViewId.DataBind();
} else {
cs.Close();
}
答案 1 :(得分:0)
我认为您的问题是您不应该执行查询然后填写数据集,只需填写数据集即可:
SqlDataAdapter da = new SqlDataAdapter();
//updated to explicitly create update command object
SqlCommand update = new SqlCommand("spInvent",cs);
update.CommandType = System.Data.CommandType.StoredProcedure;
update.Parameters.AddWithValue("@DisplayNo", displayNo);
update.Parameters.AddWithValue("@Q", Q);
da.UpdateCommand = update;
//don't need this line:
//da.UpdateCommand.ExecuteNonQuery();
DataSet ds = new DataSet();
da.Fill(ds);
gvInfo.DataSource = ds;
gvInfo.DataBind();
答案 2 :(得分:0)
这里有几件事:
UpdateCommand
。 SqlDataAdapter
的构造函数设置SelectCommand
。您需要指定使用哪个sproc来更新数据。SelectCommand
或UpdateCommand
- 当您使用DataAdapter填充DataSet
或致电Update()
时,DataAdapter会自动执行此操作它(GridView可能会为您执行此操作,具体取决于您如何连接它)。