我使用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進行更新? –