继我之前发布的问题(Two insert queries with linked fields)之后,为什么以下代码在'question_m'表中插入4个新行时,我只想插入1行?此外,以下代码在'answers'表中插入16个新行而不是4行?
以下是执行此代码后表格的屏幕截图:
'questions_m'表格 - http://i.imgur.com/tMeGAyt.png
'答案'表 - http://i.imgur.com/z3nVYAe.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();
}
}
答案 0 :(得分:0)
ExecuteScalar()通常用于从数据库返回/选择一些数据。当您执行任何DDL查询时,请使用ExecuteNonQuery。