我有一个接受对象列表的控制器,然后将其插入数据库 我已经完成了,但我认为如果有大量数据,我的代码就会出现问题。
我的代码
public void SaveAnswers(List<questionModel.SAVEDANSWER> answers, int userid)
{
string query = "INSERT INTO answer (QUESTIONID,USERANSWERID, USERID) VALUES (@qid, @aid,@uid);";
using (MySqlConnection myconn = new MySqlConnection(cmn.connstring))
{
myconn.Open();
for (int i = 0; i <= answers.Count - 1; i++)
using (MySqlCommand myCmd = new MySqlCommand(query, myconn))
{
myCmd.CommandType = System.Data.CommandType.Text;
MySqlParameter questionid = myCmd.Parameters.AddWithValue("@qid", answers[i].QUESTIONID);
myCmd.Parameters.AddWithValue("@qid", answers[i].QUESTIONID);
myCmd.Parameters.AddWithValue("@aid", answers[i].ANSWERID);
myCmd.Parameters.AddWithValue("@uid", userid);
myCmd.ExecuteNonQuery();
}
myconn.Close();
myconn.Dispose();
}
}
我在SQL Server中做了类似的事情。我将对象列表插入到数据表中,然后将数据表传递给存储过程。
在我的SQL Server存储过程中,我有一个表参数。
我可以在MySQL中做类似的事吗?
答案 0 :(得分:0)
您可以使用多个插入行方法与“列表”构建器(假设所有都是整数)
public void SaveAnswers(List<questionModel.SAVEDANSWER> answers, int userid)
{
StringBuilder query = new StringBuilder("INSERT INTO answer (QUESTIONID,USERANSWERID, USERID) VALUES";
using (MySqlConnection myconn = new MySqlConnection(cmn.connstring))
{
List<String> Rows = new List<String>();
for (int i = 0; i <= answers.Count - 1; i++)
{
Rows.Add(string.Format("({0},{1},{2})", (answers[i].QUESTIONID), (answers[i].ANSWERID),(answers[i].userId)));
}
query.Append(string.Join(",", Rows));
query.Append(";");
myconn.Open();
using (MySqlCommand myCmd = new MySqlCommand(query.ToString(), myconn))
{
myCmd.CommandType = CommandType.Text;
myCmd.ExecuteNonQuery();
}
myconn.Close();
}
}
答案 1 :(得分:-1)
如果您使用的是C#6,则可以在foreach语句中对查询进行字符串插值。
public void SaveAnswers(List<questionModel.SAVEDANSWER> answers, int userid)
{
using (MySqlConnection myconn = new MySqlConnection(cmn.connstring))
{
myconn.Open();
foreach(var item in answers)
{
//do string interpolation of your query.
var myCmd = new MySqlCommand($@"INSERT INTO answer (QUESTIONID,USERANSWERID, USERID) VALUES ({item.QUESTIONID}, {item.ANSWERID},{userid})", myconn))
myCmd.CommandType = System.Data.CommandType.Text;
myCmd.ExecuteNonQuery();
}
}
}