-1

我正在通过数组更新数据库中的值,但它仅将数组中的最后一个值更新到所有行。我究竟做错了什么?

在 .cs 文件中

BL_HotelDetails hd1 = new BL_HotelDetails();
string[] strResult = strObj.Split(',');
hd1.updateintoRoomNames(hid, strResult);

在业务逻辑层

public void updateintoRoomNames(int hid, string[] strResult)
{
    DA_HotelDetails hd2 = new DA_HotelDetails();
    hd2.updateintoRommNamesDA(hid,strResult);
}

在数据访问层

public void updateintoRommNamesDA(int hid, string[] strResult)
{
    foreach (string s in strResult) 
    {
        Connection concls = new Connection();
        SqlCommand cmd = new SqlCommand();
        string instr = "update tblRoomNames set roomnames='" + s + "' where hid=" + hid + "";

        concls.opencon();
        cmd.CommandText = instr;
        concls.executenonquery(cmd);
        concls.closecon();
    }
}
4

2 回答 2

1

您的代码似乎没问题。这里是如何工作的

说 strResult 有三个值 'Value1','Value2',Value3' 和 hid=5

第一次迭代后,房间名称将是“Value1”,其中 hid =5

在第二次迭代之后 roomnames ='Value2' where hid =5 在第三次迭代之后 roomnames='Value3' where hid =5

结果你会看到 roomnames='Value3'

如果要更改 strResult 数组中每个值的房间名称,则应使用另一个包含 hid 的整数数组,该数组将对应于 strResult

更新

我建议,创建一个整数数组来存储隐藏值,就像您创建了一个字符串 strResult 数组一样。

    int[] intNameIDs = = new int[] { 3, 4, 5 };
    int hid=22;

    public void updateintoRoomNames(int hid,int[] intNameIDs, string[] strResult)
    {
        DA_HotelDetails hd2 = new DA_HotelDetails();
        hd2.updateintoRommNamesDA(hid,intNameIDs, strResult);
    }


    public void updateintoRommNamesDA(int hid,int[] intNameIDs, string[] strResult)
    {
        int nameidIndex = 0;//index for intHids array. 
        foreach (string s in strResult)
        {
            Connection concls = new Connection();
            SqlCommand cmd = new SqlCommand();
            string instr = "update tblRoomNames set roomnames='" + s + "' where nameid=" + intNameIDs[nameidIndex] + " and Hid=" + hid;

            concls.opencon();
            cmd.CommandText = instr;
            concls.executenonquery(cmd);
            concls.closecon();

            nameidIndex++;//move to next.
        }
    }
于 2013-01-28T07:45:34.950 回答
0

根据我们的讨论。你可以像这样更新。

    public void updateintoRommNamesDA(List<Entity_HotelDetails> updatedList)
    {

        foreach (Entity_HotelDetails s in updatedList)
        {
            Connection concls = new Connection();
            SqlCommand cmd = new SqlCommand();
            string instr = "update tblRoomNames set roomnames='" + s.ROOMNAMES + "' where nameid=" + s.NAMEID + " and Hid=" + s.HID;

            concls.opencon();
            cmd.CommandText = instr;
            concls.executenonquery(cmd);
            concls.closecon();


        }
    }
于 2013-01-28T10:33:18.390 回答