如何将多个动态行值插入数据库

时间:2015-07-08 05:46:24

标签: asp.net-mvc

 public void create(account_detail c, int jobcard_id)
        {
            SqlConnection con = new SqlConnection(@"Data source =(LocalDB)\v11.0;AttachDbFilename=C:\Users\Wattabyte Inc\Documents\CarInfo.mdf;Integrated Security=True;");
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            foreach (var details in c.Data)
            {
                cmd.CommandText = "insert into child_detail values ('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "');";
                cmd.ExecuteNonQuery();
            }

        }          

我正在使用此代码,但它只采用单个值,但我想将多个值保存到数据库中?

1 个答案:

答案 0 :(得分:0)

尝试类似:

string additionalText = string.Empty;
bool needComma = false;

foreach (var details in c.Data)
{
    if (needComma)
        additionalText += ", ";
    else
        needComma = true;

    additionalText += "('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "')";
}

cmd.CommandText = "insert into child_detail values " + additionalText + ";";
cmd.ExecuteNonQuery();

基本思路 - 在foreach循环中准备teh命令字符串,然后执行一次命令。