老师上课讲的如何使用update方法更新回数据库的问题,并且附带讲了ado.net的事务处理,但我写了段代码怎么也更新不回数据库。请高手指点!DataTable dt = (DataTable)Session["Authors"];
DataTable d = dt.GetChanges(); string constr = System.Configuration.ConfigurationSettings.AppSettings["constr"].ToString();
SqlConnection mycon=new SqlConnection(constr);
SqlCommand mycom = new SqlCommand();
mycom.CommandText = "GetAllAuthors";
mycom.CommandType = CommandType.StoredProcedure;
mycom.Connection = mycon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = mycom; SqlCommandBuilder cb = new SqlCommandBuilder();
cb.DataAdapter = da; da.InsertCommand = cb.GetInsertCommand();
da.UpdateCommand = cb.GetUpdateCommand();
da.DeleteCommand = cb.GetDeleteCommand();
SqlConnection con = da.InsertCommand.Connection;
mycon.Open();
SqlTransaction tran = mycon.BeginTransaction();
da.UpdateCommand.Transaction = tran;
da.DeleteCommand.Transaction=tran;
da.InsertCommand.Transaction = tran;
try
{
da.Update(dt);
tran.Commit();
}
catch (Exception e1)
{
string s = e1.Message;
tran.Rollback();
}
finally
{
mycon.Close();
}
请高手看看我的命令是不是出问题了
DataTable d = dt.GetChanges(); string constr = System.Configuration.ConfigurationSettings.AppSettings["constr"].ToString();
SqlConnection mycon=new SqlConnection(constr);
SqlCommand mycom = new SqlCommand();
mycom.CommandText = "GetAllAuthors";
mycom.CommandType = CommandType.StoredProcedure;
mycom.Connection = mycon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = mycom; SqlCommandBuilder cb = new SqlCommandBuilder();
cb.DataAdapter = da; da.InsertCommand = cb.GetInsertCommand();
da.UpdateCommand = cb.GetUpdateCommand();
da.DeleteCommand = cb.GetDeleteCommand();
SqlConnection con = da.InsertCommand.Connection;
mycon.Open();
SqlTransaction tran = mycon.BeginTransaction();
da.UpdateCommand.Transaction = tran;
da.DeleteCommand.Transaction=tran;
da.InsertCommand.Transaction = tran;
try
{
da.Update(dt);
tran.Commit();
}
catch (Exception e1)
{
string s = e1.Message;
tran.Rollback();
}
finally
{
mycon.Close();
}
请高手看看我的命令是不是出问题了
mycom.CommandType = CommandType.StoredProcedure;//指定的存储过程返回的可能不是单表数据查询,而使用
SqlCommandBuilder cb = new SqlCommandBuilder();仅能自动处理单表查询对应的InsertCommand,UpdateCommand,DelteCommand没有贴 异常信息 ,以上供参考。请把异常贴出来,才有分析根据
另外dt是否已经AcceptChanges()
还有da.Update(dt);是否应该换成da.Update(d);
我使用不使用AcceptChanges()方法都没有关系的,他根本就没有返回到数据库
是否使getchanges()方法进行过滤,只是提高ado.net的效率问题。我都快哭死了。