我正在使用 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/