C#更新数据库

时间:2011-10-03 17:37:15

标签: c# database oledb

我正在使用Oledb作为我的数据库,并且每当用户点击并点按时,我都会尝试更新数据库中的“状态”列。所以就是这样......

当用户点击时,它将查询db的“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();
        }

    }

3 个答案:

答案 0 :(得分:1)

执行标量返回select的第一行的第一列。您正在执行更新,更好的选择是使用executenonquerry。

答案 1 :(得分:1)

您打算致电ExecuteNonQuery,但您写了ExecuteScalar

请检查您的行

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

我想它应该是

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

答案 2 :(得分:0)

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