SqlDataAdapter .update功能未更新

本文关键字:更新 功能 update SqlDataAdapter | 更新日期: 2023-09-27 18:02:46

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

我尝试通过sqlcommnadBuilder和其他方式,但它没有更新。

注意:在XMl文件中,我有2或3行与数据库具有相同的"RSN"值,但其他列值不同,我需要更新I Got Exception as

Update在传递DataRow时需要一个有效的InsertCommand

当我使用CommandBuilder时,我得到异常

违反PRIMARY KEY约束'PK_RSN_All'。无法在对象'dbo.RSN_All'中插入重复键。语句已被终止。

but this Rows Already exists in 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"] );
    }
}

SqlDataAdapter .update功能未更新

试试这个:

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");
    }
}