SqlDataAdapter .update函数未更新

时间:2014-05-12 06:50:30

标签: c# sql-server

我在Sql数据库中有一个表调用RSN_ALl ,我想根据我的XML文件更新它的几行,基于RSN列主键。

我尝试使用sqlcommnadBuilder和其他方式但不更新。

注意:在XMl文件中,我有2或3行具有相同的" RSN"值为DataBase但其他列值不同,我需要更新

我有例外
  

更新在传递DataRow时需要有效的InsertCommand   用新行收集。

当我使用CommandBuilder时,我得到了Exception as

  

违反PRIMARY KEY约束' PK_RSN_All'。无法在对象' dbo.RSN_All'中插入重复的密钥。   声明已经终止。

但此行已存在于Sql DataBase TAble中

using (SqlConnection cn = new SqlConnection(SqlHelper.ConString))
{
    DataSet DsXmlData = new DataSet();                                 
    DsXmlData.ReadXml(xml_file_path);
    DsXmlData.Tables["RSN_ALL"].PrimaryKey = new DataColumn[] { DsXmlData.Tables["RSN_ALL"].Columns["RSN"] };

    using (SqlDataAdapter da = new SqlDataAdapter("select * from RSN_All", cn))
    {
        DataSet ds = new DataSet();
        da.Fill(ds);  

        string updataCommand ="update RSN_All set Batch_M_id = @Batch_M_id ,Parent_RSN =@Parent_RSN, Pkg_Location =@Pkg_Location, CompanyId =@CompanyId where RSN =@RSN";
        SqlCommand cmd = new SqlCommand(updataCommand, cn);
        cmd.Parameters.Add("@Batch_M_id", SqlDbType.BigInt, 0, "Batch_M_id");
        cmd.Parameters.Add("@Parent_RSN", SqlDbType.VarChar , 20, "Parent_RSN");
        cmd.Parameters.Add("@Pkg_Location", SqlDbType.NVarChar , 100, "Pkg_Location");
        cmd.Parameters.Add("@CompanyId", SqlDbType.Int , 0, "CompanyId");
        cmd.Parameters.Add("@RSN", SqlDbType.VarChar , 20, "RSN");
        da.UpdateCommand = cmd;

        da.Update(DsXmlData.Tables["RSN_ALL"] );
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个:

using (SqlConnection cn = new SqlConnection(SqlHelper.ConString))
{
    DataSet DsXmlData = new DataSet();                                 
    DsXmlData.ReadXml(xml_file_path);
    DsXmlData.Tables["RSN_ALL"].PrimaryKey = new DataColumn[] { DsXmlData.Tables["RSN_ALL"].Columns["RSN"] };

    using (SqlDataAdapter da = new SqlDataAdapter("select * from RSN_All", cn))
    {
        DataSet ds = new DataSet();
        da.Fill(ds, "RSN_ALL");  

        string updataCommand ="update RSN_All set Batch_M_id = @Batch_M_id ,Parent_RSN =@Parent_RSN, Pkg_Location =@Pkg_Location, CompanyId =@CompanyId where RSN =@RSN";
        SqlCommand cmd = new SqlCommand(updataCommand, cn);
        cmd.Parameters.Add("@Batch_M_id", SqlDbType.BigInt, 0, "Batch_M_id");
        cmd.Parameters.Add("@Parent_RSN", SqlDbType.VarChar , 20, "Parent_RSN");
        cmd.Parameters.Add("@Pkg_Location", SqlDbType.NVarChar , 100, "Pkg_Location");
        cmd.Parameters.Add("@CompanyId", SqlDbType.Int , 0, "CompanyId");
        cmd.Parameters.Add("@RSN", SqlDbType.VarChar , 20, "RSN");
        da.UpdateCommand = cmd;

        da.Update(ds, "RSN_ALL");
    }
}