在我的代码上获取NullpointerException

时间:2014-10-28 11:34:06

标签: c# sql oracle

我在这段代码上得到了一个N​​ullpointer:

public void InsertImportantMsg (string msg, DateTime toDay, int visible)
    {

            connection.Open ();
            string query = "UPDATE IMPORTANTMESSAGE SET MESSAGES=':msg', DATETIME=':toDay', " +
                "LABELVISIBILITY=':visible'";
            connection.CreateCommand ();
            cmd.CommandText = query;
            cmd.Parameters.Add (":msg", msg);
            cmd.Parameters.Add (":toDay", toDay);
            cmd.Parameters.Add(":visible", visible);

            cmd.ExecuteNonQuery ();

    }

特别是在这一行:

cmd.CommandText = query;

我正在传递参数。我的更新声明是否有问题,我没有意识到?

(我知道代码应该在try catch中,但现在是有目的的,所以不要看那个)

由于

1 个答案:

答案 0 :(得分:1)

例外的直接原因是您尚未分配 cmd值。 实施可能就像那样

public void InsertImportantMsg (string msg, DateTime toDay, int visible) {
  connection.Open();

  // Put IDisposable into using...
  using (var cmd = connection.CreateCommand()) {
    // Format query to be readble
    cmd.CommandText = 
      @"UPDATE IMPORTANTMESSAGE
           SET MESSAGES = :msg, -- <- you don't need apostrophes here...
               DATETIME = :toDay,
               LABELVISIBILITY = :visible";

    cmd.Parameters.Add(":msg", msg);
    cmd.Parameters.Add(":toDay", toDay);

    //TODO: Check this - Oracle doesn't support boolean is SQL 
    cmd.Parameters.Add(":visible", visible);  

    cmd.ExecuteNonQuery(); 
  }
}