我使用Oledb作为我的数据库,并且我试图在用户点击和点击时更新我的数据库中的“状态”列。所以它就像这样..C#更新数据库
当用户点击时,它会查询数据库的“状态”列,它是之前的“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();
}
}
你为什么要调用ExecuteScalar进行更新? –