【问题标题】:NullReferenceException was caught...?NullReferenceException 被捕获...?
【发布时间】:2013-07-18 10:44:36
【问题描述】:

运行 foreach 循环后。我在第二项上收到 NullReferenceException,因为查询结果为空。但我有更多项目可用于同一查询并在richTextBox1 上获得结果。如果有任何空结果,我可以继续 foreach 循环吗?

foreach (string Items in listBox4.Items)
{
    using (OracleCommand crtCommand = new OracleCommand("select REGEXP_REPLACE(dbms_metadata.get_ddl('TABLE','" + Items + "'),('" + txtSrcUserID.Text + "...'),'', 1, 0, 'i') from dual", conn1))                           
    {
        richTextBox1.AppendText(Environment.NewLine);
        richTextBox1.AppendText(crtCommand.ExecuteScalar().ToString() + ";");
        richTextBox1.AppendText(Environment.NewLine);
    }                                                      
}

【问题讨论】:

  • 你有一个 SQL 注入漏洞。

标签: c# foreach


【解决方案1】:

这是危险的编程。你真的应该检查null。假设你的循环会变得更大.. 我会包含一个continue 并让它更明显你正在做什么以提高可读性。如果不需要,请省略 continue

var result = crtCommand.ExecuteScalar();

if (result != null) {
    richTextBox1.AppendText(Environment.NewLine);
    richTextBox1.AppendText(result.ToString() + ";");
    richTextBox1.AppendText(Environment.NewLine);
}
else {
    continue;
}

// any other code here.

【讨论】:

  • 谢谢,这是答案。
【解决方案2】:

crtCommand.ExecuteScalar().ToString() 更改为(crtCommand.ExecuteScalar() ?? string.Empty).ToString()。这在逻辑上等价于:

  object dbResult = crtCommand.ExecuteScalar();
  if(dbResult == null) 
  {
     richTextBox1.AppendText(";");
  }
  else
  {
     richTextBox1.AppendText(dbResult.ToString() + ";");
  }

如果您想完全忽略空结果而不是将其视为空字符串,请使用@SimonWhitehead 的代码

【讨论】:

  • 你可能想解释一下??运算符。
  • 我是从 PHP 到 C# 的,我从来没有遇到过 ??运营商直到最近,所以我不认为每个人都有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多