ASP.Net c# - MySQLTransaction多重插入
本文关键字:插入 MySQLTransaction Net ASP | 更新日期: 2023-09-27 18:14:07
从我以前的问题张贴在这里(两个插入查询链接字段),为什么下面的代码插入4个新行在'question_m'表,当我想只插入1行?此外,以下代码在"答案"表中插入16行新行,而不是4行?
下面是执行这段代码后的表的屏幕截图:
'questions_m'表- https://i.stack.imgur.com/f3DrZ.png
'answers'表- https://i.stack.imgur.com/PaTvO.png
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
using (MySqlTransaction tr = conn.BeginTransaction())
{
string queryUpdateQuestions = @"INSERT INTO questions_m (module_id, author_id, approved, question, type) VALUES (@module_id, @author_id, @approved, @question, @type);
SELECT LAST_INSERT_ID()";
using (MySqlCommand cmdUpdateQuestions = new MySqlCommand(queryUpdateQuestions, conn, tr))
{
cmdUpdateQuestions.Parameters.Add("@module_id", MySqlDbType.VarChar);
cmdUpdateQuestions.Parameters["@module_id"].Value = ddlModules.SelectedValue.ToString();
cmdUpdateQuestions.Parameters.Add("@author_id", MySqlDbType.VarChar);
cmdUpdateQuestions.Parameters["@author_id"].Value = Session["UserID"].ToString();
cmdUpdateQuestions.Parameters.Add("@approved", MySqlDbType.VarChar);
cmdUpdateQuestions.Parameters["@approved"].Value = 'N';
cmdUpdateQuestions.Parameters.Add("@question", MySqlDbType.VarChar);
cmdUpdateQuestions.Parameters["@question"].Value = txtQuestion.Text;
cmdUpdateQuestions.Parameters.Add("@type", MySqlDbType.VarChar);
cmdUpdateQuestions.Parameters["@type"].Value = ddlQuestionType.SelectedValue.ToString();
int lastQuestionID = Convert.ToInt32(cmdUpdateQuestions.ExecuteScalar());
ViewState["lastQuestionID"] = lastQuestionID;
}
string queryUpdateAnswers = @"INSERT INTO answers (question_id, answer, correct) VALUES (@question_id, @answer, @correct);
SELECT LAST_INSERT_ID()";
using (MySqlCommand cmdUpdateAnswers = new MySqlCommand(queryUpdateAnswers, conn, tr))
{
cmdUpdateAnswers.Parameters.Add("@answer", MySqlDbType.VarChar);
cmdUpdateAnswers.Parameters.Add("@question_id", MySqlDbType.Int32);
cmdUpdateAnswers.Parameters.Add("@correct", MySqlDbType.VarChar);
int lastAnswerID = 0;
int a = Convert.ToInt32(ddlNoOfAnswers.SelectedValue.ToString());
for (int b = 1; b <= a; b++)
{
cmdUpdateAnswers.Parameters["@answer"].Value = ((TextBox)this.FindControl("txtAnswer" + b)).Text;
cmdUpdateAnswers.Parameters["@question_id"].Value = Convert.ToInt32(ViewState["lastQuestionID"]);
if (b == 1)
{
cmdUpdateAnswers.Parameters["@correct"].Value = "Y";
}
else
{
cmdUpdateAnswers.Parameters["@correct"].Value = null;
}
lastAnswerID = Convert.ToInt32(cmdUpdateAnswers.ExecuteScalar());
}
}
tr.Commit();
}
}
ExecuteScalar()通常用于从数据库中返回/选择一些数据。使用ExecuteNonQuery代替执行任何DDL查询。