2011-10-03 144 views
1

我使用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(); 
     } 

    } 
+0

你为什么要调用ExecuteScalar进行更新? –

回答

1

你打算叫ExecuteNonQuery,但你写ExecuteScalar

请检查您的线

// 3. Call ExecuteNonQuery to send command 
str = cmd1.ExecuteScalar().ToString(); 

我想这应该是

// 3. Call ExecuteNonQuery to send command 
str = cmd1.ExecuteNonQuery().ToString(); 
+0

谢谢你们,我明白了!是的,有点讽刺的是,我没有执行我写的内容,因为有些人坚持我使用ExecuteScalar而不是ExecuteNonQuery,所以我没有真正尝试NonQuery,直到你们提到。我很笨:P –

1

执行标量返回select的第一行的第一列。您正在执行更新,更好的选择是使用executenonquerry。

+0

我认为这很具有讽刺意味,他已经将你的答案作为直接调用ExecuteScalar之上的评论的一部分。 –

0

这很可能是因为cmd1.ExecuteScalar()回报null和你正试图调用其上的ToString()方法。 UPDATE查询通常不会返回任何结果,因此您可能不应该使用ExecuteScalar而是ExecuteNonQuery来执行它。