开发者

Store Array Data to Database

开发者 https://www.devze.com 2023-02-26 03:03 出处:网络
I\'m trying to store data from some arrays into the database but only the last index of the arra开发者_如何学Pythonys were stored. I know I need to fix the looping part but I\'ve no idea how to. Below

I'm trying to store data from some arrays into the database but only the last index of the arra开发者_如何学Pythonys were stored. I know I need to fix the looping part but I've no idea how to. Below is the code.

for (int i = 0; i < 5; i++)
        {
            cmd.Parameters["Mon1"].Value = newTA.MonAry[i];
            cmd.Parameters["Tue1"].Value = newTA.TueAry[i];
            cmd.Parameters["Wed1"].Value = newTA.WedAry[i];
            cmd.Parameters["Thu1"].Value = newTA.ThuAry[i];
            cmd.Parameters["Fri1"].Value = newTA.FriAry[i];
        }


You need to create and execute the command inside the loop:

for (int i = 0; i < 5; i++)
{
    using (var conn = new SqlConnection("Some Connection String"))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = "INSERT INTO foo (...) VALUES (...)";
        cmd.Parameters["Mon1"].Value = newTA.MonAry[i];
        cmd.Parameters["Tue1"].Value = newTA.TueAry[i];
        cmd.Parameters["Wed1"].Value = newTA.WedAry[i];
        cmd.Parameters["Thu1"].Value = newTA.ThuAry[i];
        cmd.Parameters["Fri1"].Value = newTA.FriAry[i];
        cmd.ExecuteNonQuery();
    }
}


if you are using sqlserver then you can pass this as table type parameter so that mutiple rows can be inserted see this link

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号