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();
}
}
我正在使用此代码,但它只采用单个值,但我想将多个值保存到数据库中?
答案 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命令字符串,然后执行一次命令。