【问题标题】:Object reference not set to an instance of an object c# error [duplicate]对象引用未设置为对象c#错误的实例[重复]
【发布时间】:2013-11-28 14:47:11
【问题描述】:

我需要检查一条记录是否保存到数据库中。如果它保存在数据库中,请打开另一个表单,否则会显示一条消息,表明它不在数据库中。
如果记录不在数据库中,我会收到此错误Object reference not set to an instance of an object.
这是我的代码,请帮我在这里找到错误:

string cmdStr = "Select NO from COM_LIST_EXPORT where NO = '" + txtNO.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, CN);
int count = (int)cmd.ExecuteScalar();
if (count == Convert.ToInt32(txtNO.Text))
{
    Archive_Sader dd = new Archive_Sader();
    dd.Show();
}

else
{
    MessageBox.Show("please save first");
}

【问题讨论】:

标签: c# sql


【解决方案1】:

来自SqlCommand.ExecuteScalar

返回值

结果集中第一行的第一列,或null 如果结果集为空,则引用。

这就是为什么当结果没有行时,您实际上尝试将null 转换为Int32

看起来你需要改变你的线路;

int count = Convert.ToInt32(cmd.ExecuteScalar());

因为Convert.ToInt32在参数为null时返回0

返回值

一个 32 位有符号整数,它与 value 中的数字等价,或 如果值为 null,则为 0(零)。

您应该始终使用parameterized queries。这种字符串连接对SQL Injection 攻击开放。

例如;

string cmdStr = "Select NO from COM_LIST_EXPORT where NO = @NO";
SqlCommand cmd = new SqlCommand(cmdStr, CN);
cmd.Parameters.AddWithValue("@NO", txtNO.Text);
...

【讨论】:

  • @Downvoter 至少愿意发表评论,这样我才能知道我可能错在哪里?
  • 我看不出有任何理由对此投反对票。我的 +1 ..
  • @SriramSakthivel 看起来讨厌的人会讨厌:)
【解决方案2】:

ExecuteScalar 在没有找到记录时返回null

因此,当您尝试投射 null -> int 时,您会得到一个 NullReferenceException

试试这个。

int count = Convert.ToInt32(cmd.ExecuteScalar());

Convert.ToInt32 将在参数为null 时返回0

【讨论】:

    猜你喜欢
    • 2013-07-07
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多