C#更新数据库
我使用Oledb作为我的数据库,每当用户点击输入和输出时,我都会尝试更新数据库中的“状态”列。所以事情是这样的 当用户点击时,它将查询数据库的“状态”列,它以前是“输入”、“输出”还是空白。查询为“入”时,当前状态为“出”,反之亦然。更新的工作方式完全符合我的要求,除了每次运行时都会出现警告“NullReferenceException未处理”,我无法继续运行它:str=cmd1.ExecuteScalar().ToString()强> 我对C#很陌生,如果有人能向我详细解释我如何解决这个问题,那就太好了。谢谢大家!C#更新数据库,c#,database,oledb,C#,Database,Oledb,我使用Oledb作为我的数据库,每当用户点击输入和输出时,我都会尝试更新数据库中的“状态”列。所以事情是这样的 当用户点击时,它将查询数据库的“状态”列,它以前是“输入”、“输出”还是空白。查询为“入”时,当前状态为“出”,反之亦然。更新的工作方式完全符合我的要求,除了每次运行时都会出现警告“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返回select的第一行的第一列。您正在执行更新。更好的选择是使用ExecuteQuery。您打算调用
ExecuteQuery
,但您编写了ExecuteCalar
请检查您的线路
// 3. Call ExecuteNonQuery to send command
str = cmd1.ExecuteScalar().ToString();
我想应该是这样
// 3. Call ExecuteNonQuery to send command
str = cmd1.ExecuteNonQuery().ToString();
这很可能是因为
cmd1.ExecuteScalar()
返回null
,并且您正试图对其调用ToString()
方法。更新查询通常不会返回任何结果,因此您可能不应该使用ExecuteScalar
,而应该使用ExecuteNonQuery
来执行它。为什么您要调用ExecuteScalar进行更新?我觉得很讽刺的是,他在调用ExecuteScalar的正上方的注释中包含了您的答案。谢谢大家,我明白了!是的,有点讽刺的是,我没有执行我写的东西,因为有些人坚持我使用ExecuteScalar而不是ExecuteOnQuery,所以在你们提到之前,我实际上没有尝试非查询。我很笨:P