从数据库中检索可能为null的内容

时间:2013-04-29 20:30:10

标签: c# mysql

我的代码是基本的:

//get connection 
//make connection string which returns one value
//open connection
string picture = command.ExecuteScalar().ToString();
//close connection

查询返回null的可能性就在那里。那么如何判断它是否为null然后将其存储到我的字符串中呢?我上面使用的东西不起作用,因为字符串抛出异常。那么我可以暂时将值存储到某个东西然后将其折回到字符串中吗?我不想运行两个ExecuteScalars来查明它的null是否先存储它。

2 个答案:

答案 0 :(得分:0)

我通常这样做:

string picture = null;
object picTemp = command.ExecuteScalar();
if (picTemp != null && picTemp != System.DBNull.Value) {
   picture = (string)picTemp;
}
如果未返回任何结果,

picTemp将为null。如果返回结果但结果的值为null,则为System.DBNull.Value

答案 1 :(得分:0)

您需要做的就是检查null

string picture = command.ExecuteScalar() as string;
if(picture == null)
{
    // Handle the NULL case
}

// Do something with picture...

正如我在文档中看到的那样,您不必检查System.DBNull.Value,因为ExecuteScalar()不应该返回它。

  

返回值
  键入:System.Object
  第一行的第一列   如果是结果集,或者是null引用(在Visual Basic中为Nothing)   结果集为空。最多返回2033个字符。

来自http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx