C# updating database
I'm using Oledb as my database and I'm trying to update the "Status" column in my db whenever a user taps in and taps out. So it goes like this..
When a user taps, it will query the "Status" column of the db whether it was "IN", "OUT" or blank previously. When queried to be "IN", the status will be set to "OUT" currently and vice versa. The updatings are all working exactly the way I want except that the warning "NullReferenceException was unhandled" that keeps appearing at this line everytime I run it and I can't continue running further: str = cmd1.ExecuteScalar().ToString();
I'm very new to C# and it'd be good if someone can explain to me in de开发者_运维问答tail how I can fix this. Thank you!
// 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();
}
}
You intend to call ExecuteNonQuery
but you wrote ExecuteScalar
Please check your line
// 3. Call ExecuteNonQuery to send command
str = cmd1.ExecuteScalar().ToString();
I guess it should be
// 3. Call ExecuteNonQuery to send command
str = cmd1.ExecuteNonQuery().ToString();
Execute scalar returns the first column of the first row of a select. You are performing an update a better choice would be to use executenonquerry.
This is quite likely because cmd1.ExecuteScalar()
returns null
and you are trying to invoke the ToString()
method on it. An UPDATE query usually do not return any results, so you probably should not be using ExecuteScalar
but rather ExecuteNonQuery
to execute it.
精彩评论