无法在asp.net中将数组元素更新到数据库中

时间:2013-01-28 07:07:38

标签: c# database

我通过数组更新数据库中的值,但它只将数组中的最后一个值更新为所有行。我做错了什么?

在.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();
    }
}

2 个答案:

答案 0 :(得分:1)

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

假设strResult有三个值'Value1','Value2',Value3' 并且hid = 5

在第一次迭代后,房间名称将为'Value1',其中hid = 5

在第二次迭代后,roomnames ='Value2',其中hid = 5 在第3次迭代后,roomnames ='Value3',其中hid = 5

因此你会看到roomnames ='Value3'

如果你想更改strResult数组中每个值的空间名,那么你应该使用另一个包含hid的整数数组,这些整数将对应于strResult

<强>更新

我建议,创建一个Integers数组来存储hid值,就像你创建了一个String 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.
        }
    }

答案 1 :(得分: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();


        }
    }