在c#和Access中更新当前记录不起作用

本文关键字:记录 不起作用 更新 Access | 更新日期: 2023-09-27 17:50:12

我有一个表单,如果用户在文本框中输入隐藏问题的正确答案,它将进入数据库中随机选择的下一个记录,并在数据库的玩家表中的playerscore列添加+1。但是,分数没有更新,无论是在数据库中还是在标签中。

我已经从这篇文章中删除了所有其他代码,例如连接字符串,但它在那里并且连接正在建立。

    private void SubmitAnswer_Click(object sender, EventArgs e)
    {
        int score = 0;
        if (WordBox.Text == WordLbl.Text)
        {
            TopLbl.Text = "Well done! :)";
            synthesizer.SpeakAsync("Well done. Now try answering this...");
            this.BackColor = System.Drawing.Color.OliveDrab;
            String command = "SELECT TOP 1 * FROM Questions ORDER BY Rnd(-(100000*ID)*Time())";
            try
            {
                FillDataTable(command);
                ShowRow(currentRow);
                score++; // Adding one each time the player spells the word correctly.
                ScoreLabel.Text = "Score: " + score.ToString(); // Update the label to display new score.
                myAdapter.SelectCommand.CommandText = "UPDATE Questions SET players = playerscore + 1 WHERE ID =" + currentRow;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            synthesizer.SpeakAsync("Answer the question" + WordLbl.Text); 
        }
        else
        {
            TopLbl.Text = "Try answering this question again";
            synthesizer.SpeakAsync("Try answering this question again");
            this.BackColor = System.Drawing.Color.Red; color on the form.
        }
    }

我怀疑这可能是由于currentRow。在程序的顶部:

// Index of the current record private int currentRow = 0;

ShowRow类

    private void DisplayRow(int rowIndex)
    {
        if (myDataTable.Rows.Count == 0)
        return; 
        if (rowIndex >= myDataTable.Rows.Count)
        return; 
        try
        {
            DataRow row = myDataTable.Rows[rowIndex];
            KS1WordLbl.Text = row["Word"].ToString();
            synthesizer.SpeakAsync("Answer the question" + WordLbl.Text);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error in DisplayRow : 'r'n" + ex.Message);
        }
    } 

在c#和Access中更新当前记录不起作用

假设myDataTable是由FillDataTable和它的作用域填充,你应该能够更新你的where子句

where id = " + myDataTable.Rows[0].[id].ToString()

你当前尝试做的更像是一个就地更新你需要做的是提取记录Id并使用它来告诉db要更新的记录

请注意,虽然您不必担心SQL注入攻击,因为id不是由用户控制的,但您应该看看参数化查询。