C#更新数据库

标签 c# database oledb

我正在使用 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();
        }

    }

最佳答案

您打算调用 ExecuteNonQuery 但您编写了 ExecuteScalar

请检查您的线路

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

应该是吧

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

关于C#更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7638582/

相关文章:

mysql - 无法获得正确的分组依据表达式

database - 对于 Vertica 一次只能使用一个数据库的限制,是否有解决方法?

database - Postgres 架构最佳实践

c# - 如何在 DOTween 中实现异步?

c# - 嵌套列表上的 Linq - 选择所有 ID

c# - XPath 或,替代方案

c# - 获取系统上安装的所有 Access ACE.OLEDB 驱动程序的列表

c# - .Net/C# 客户端应用程序的 WITSML api 库?

c# - SQL 查询 : Select Column1, 行数 (criteria1),行数 (criteria2)

c# - 使用 oledb netting "_xlnm#_FilterDatabase"作为工作表名称的多工作表导入