c#更新数据库

本文关键字:数据库 更新 | 更新日期: 2023-09-27 18:10:24

我使用Oledb作为我的数据库,我试图在我的数据库中更新"状态"列,每当用户敲入和敲出时。所以它是这样的…

当用户点击时,它将查询数据库的"Status"列之前是"IN","OUT"还是空白。当查询为"IN"时,当前状态将设置为"OUT",反之亦然。更新都是完全按照我想要的方式工作,除了警告"NullReferenceException未处理",每次我运行它时都出现在这行,我不能继续进一步运行:str = cmd1.ExecuteScalar().ToString();

我对c#非常陌生,如果有人能向我详细解释如何解决这个问题就太好了。谢谢你!

        // prepare command string
        string selectString = @"SELECT Status FROM jiahe where [Tag ID] = '" + textBox1.Text + "'";
        // 1. Instantiate a new command with command text only
        OleDbCommand cmd = new OleDbCommand(selectString, objConnection);
        // 2. Set the Connection property
        cmd.Connection.Open();
        // 3. Call ExecuteNonQuery to send command
        string str = cmd.ExecuteScalar().ToString();
        cmd.Connection.Close();
        if (str.Length == 2 || str.Length == 0)
        {
            //MessageBox.Show("Status: " + str);
            // prepare command string
            string updateString = @"update jiahe set Status = 'OUT' where [Tag ID] = '" + textBox1.Text + "'";
            // 1. Instantiate a new command with command text only
            OleDbCommand cmd1 = new OleDbCommand(updateString, objConnection);
            // 2. Set the Connection property
            cmd1.Connection.Open();
            // 3. Call ExecuteNonQuery to send command
            str = cmd1.ExecuteScalar().ToString();
            MessageBox.Show("Status: OUT");
            cmd1.Connection.Close();

        }
        else
        {
            //string str1 = cmd2.ExecuteScalar().ToString();
            //MessageBox.Show("Status: " + str);
            // prepare command string
            string updateString = @"update jiahe set Status = 'IN' where [Tag ID] = '" + textBox1.Text + "'";
            // 1. Instantiate a new command with command text only
            OleDbCommand cmd1 = new OleDbCommand(updateString, objConnection);
            // 2. Set the Connection property
            cmd1.Connection.Open();
            // 3. Call ExecuteNonQuery to send command
            //string str1 = cmd2.ExecuteScalar().ToString();
            str = cmd1.ExecuteScalar().ToString();
            MessageBox.Show("Status: IN");
            cmd1.Connection.Close();
        }
    }

c#更新数据库

您想调用ExecuteNonQuery,但您写的是ExecuteScalar

请检查您的线路

// 3. Call ExecuteNonQuery to send command
str = cmd1.ExecuteScalar().ToString();

我想应该是

// 3. Call ExecuteNonQuery to send command
str = cmd1.ExecuteNonQuery().ToString();

Execute scalar返回select的第一行的第一列。如果要执行更新,最好使用executenonquery .

这很可能是因为cmd1.ExecuteScalar()返回null,而您正试图调用ToString()方法。UPDATE查询通常不返回任何结果,因此您可能不应该使用ExecuteScalar,而应该使用ExecuteNonQuery来执行它。