日期:2014-05-18  浏览次数:20837 次

能否用SqlDataAdapter.Update() 添加数据
正常的方法一是这样:
string   str= "Insert   into... ";
cmd.CommandText   =   str;
cmd.ExecuteNonQuery();

-----------------
现在我希望用第二种方法:在DataSet增加一行,然后用SqlDataAdapter.Update()完成插入操作.比如:
DataRow   row   =   ds.Tables[0].NewRow();;
row[1]   =   " ";
row[2]= " ";
ds.Tables[0].Rows.Add(row);
SqlDataAdapter.Update(ds);
....

第二种方法提示错误: "当传递具有新行的   DataRow   集合时,更新要求有效的InsertCommand。 "
请问怎么做?

------解决方案--------------------
SqlCommandBuilder scb=new SqlCommandBuilder(da);
------解决方案--------------------
/// <summary>
/// 追加信息
/// </summary>
private void AddInfor()
{
try
{
SqlDataAdapter thisAdapter = new SqlDataAdapter( "select * from TB_Users ", thisConnection);
SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
DataSet thisDataSet = new DataSet();
thisAdapter.Fill(thisDataSet, "TB_Users ");
DataRow thisRow = thisDataSet.Tables[ "TB_Users "].NewRow();
thisRow[ "UserName "] = txtName.Text;
thisRow[ "UserPws "] = txtPws.Text;
thisRow[ "Status "] = txtState.Text;
thisRow[ "Remark "] = txtRemark.Text;
thisRow[ "timestamp "] = Convert.ToDateTime(System.DateTime.Now);
thisDataSet.Tables[ "TB_Users "].Rows.Add(thisRow);
thisAdapter.Update(thisDataSet, "TB_Users ");
thisConnection.Close();

}
catch (Exception err)
{
MessageBox.Show( "追加失败 ");
}
}
------解决方案--------------------
使用Adapter也需要指定其用于数据库操作的相关Commander对象 当然如果你的数据表如果有主键,则可以使用CommanderBuilder来生成Adapter的相关命令 例如:
string sqlstr = "select * from table1 ";//table1必须有主键且主键信息包含在返回的结果集中
da = new OleDbDataAdapter(sqlstr, conn);
ds = new DataSet();
da.Fill(ds);
OleDbCommandBuilder dcmdb = new OleDbCommandBuilder(da);
……
da.Update(ds);
ds.AcceptChanges();