gpt4 book ai didi

c# - 使用 MySQL 数据填充 ArrayList

转载 作者:行者123 更新时间:2023-11-29 07:57:48 25 4
gpt4 key购买 nike

我正在尝试使用数据库中的字段(“answer”和“answer_id”)填充两个 ArrayList(listOfAnswers 和 listOfAnswerIDs)。

当字符串 cmdText 中的 Question_id=1 时,以下代码似乎工作得很好。但是,如果我将其更改为 2 或 3,ArrayList 仍为空,我不知道为什么。有什么想法吗?

我认为这与字符串 cmdGetAnswersQuery 有关,因为“SELECT * FROM Answers WHERE Question_id=2”有效...

    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
MySqlDataReader reader;

ArrayList listOfAnswerIDs = new ArrayList();
ArrayList listOfAnswers = new ArrayList();
try
{
conn.Open();
string cmdText = "SELECT * FROM questions_t WHERE question_id=2";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("@ModuleID", MySqlDbType.Int32);
cmd.Parameters["@ModuleID"].Value = ddlModules.SelectedValue;

reader = cmd.ExecuteReader();

if (reader.Read())
{
lblQuestion.Text = reader["question"].ToString();
ViewState["QuestionID"] = reader["question_id"].ToString();
ViewState["AnswerID"] = reader["correct_answer_id"].ToString();

reader.Close();

string cmdGetAnswersQuery = "SELECT * FROM answers WHERE question_id=@QuestionID";
MySqlCommand cmdGetAnswers = new MySqlCommand(cmdGetAnswersQuery, conn);
cmdGetAnswers.Parameters.Add("@QuestionID", MySqlDbType.Int32);
cmdGetAnswers.Parameters["@QuestionID"].Value = ViewState["AnswerID"];

reader = cmdGetAnswers.ExecuteReader();

while (reader.Read())
{
listOfAnswerIDs.Add(reader["answer_id"].ToString());
listOfAnswers.Add(reader["answer"].ToString());
}
reader.Close();
populateAnswers(listOfAnswers, listOfAnswerIDs);
}
else
{
reader.Close();
lblError.Text = "(no questions found)";
}
}
catch
{
lblError.Text = "Database connection error - failed to insert record.";
}
finally
{
conn.Close();
}

实际的数据库内容如下所示: http://i.imgur.com/3S4lV60.png http://i.imgur.com/8A913xF.png

最佳答案

我不能肯定地说这就是问题所在,但我首先要查看的是这行代码:

cmdGetAnswers.Parameters["@QuestionID"].Value = ViewState["AnswerID"];

我怀疑您希望它是 ViewState["QuestionID"]

关于c# - 使用 MySQL 数据填充 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24660632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com