如何将数据库NULL值传递给字符串变量?

时间:2013-09-20 20:24:16

标签: c# sql

基本上,如果参数以NULL形式出现,我想将其作为数据库NULL发送到数据库。因此(查看下面代码中的注释):

[HttpPost]
    public void UpdateTitle(Title title)
    {
      string query = null;
      string description = "";
      string episodeAKA = "";

      if (title.Description != null)
      {
        description = "'" + title.Description + "'";
      }
      else
      {
        //here's where description should be a DBNULL. 
      }

      if (title.EpisodeAKA == null)
      {
        title.EpisodeAKA = "NULL";
      }

      myConnection.Open();
      if (title.Operation == 'U')
      {
        query = "UPDATE dbo.AWD_Titles SET AwardStatusId = " + title.AwardStatus + ", Description = " + description + ", IsVerified = " + title.IsVerified + ", EpisodeAKA = '" + title.EpisodeAKA + "' WHERE AwardTitleId = " + title.AwardTitleId + " SELECT SCOPE_IDENTITY()";
      }
      var cmd = new SqlCommand(query, myConnection);
      cmd.ExecuteScalar();
      myConnection.Close();
    }
  }

这是Title的课程:

public class Title
{
  public int AwardTitleId
  {
    get;
    set;
  }

  public int AwardStatus
  {
    get;
    set;
  }

  public int IsVerified
  {
    get;
    set;
  }

  public string EpisodeAKA
  {
    get;
    set;
  }

  public string Description
  {
    get;
    set;
  }

  public char Operation
  {
    get;
    set;
  }
}

5 个答案:

答案 0 :(得分:6)

原始代码有几个基本错误。这演示了如何正确,包括如何设置DBNull:

[HttpPost]
public void UpdateTitle(Title title)
{
    string query; 
    if (title.Operation == 'U')
    {
        query = 
            "UPDATE dbo.AWD_Titles" + 
            " SET AwardStatusId = @AwardStatusID , Description = @Description , IsVerified= @IsVerified , EpisodeAKA= @EpisodeAKA" + 
            " WHERE AwardTitleId= @AwardTitleId ;" + 
            " SELECT SCOPE_IDENTITY();";
    } else {
       query="";
       //presumably you have a slightly different query string for inserts.
       //Thankfully, they should have pretty much the same set of parameters.
       //If this method will really only be called for updates, the code is quite a bit simpler
    }

    //instead of a shared myConnection object, use a shared connection string.
    // .Net is set up so that you should be creating a new connection object for most queries.
    // I know it sounds backwards, but that's really the right way to do it.
    // Create the connection in a using(){} block, so that you guarantee it is
    //    disposed correctly, even if an exception is thrown.
    using (var cn = new SqlConnection(myConnectionString))
    using (var cmd = new SqlCommand(query, cn))
    {
        //guessing at database types, lengths here. Fix with actual column types
        cmd.Parameters.Add("@AwardStatusId", SqlDbType.Int).Value = title.AwardStatus;
        cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 250).Value = title.Description;
        cmd.Parameters.Add("@IsVerified", SqlDbType.Bit).Value = title.IsVerified;
        cmd.Parameters.Add("@EpisodeAKA", SqlDbType.NVarChar, 100).Value = title.EpisodeAKA;
        cmd.Parameters.Add("@AwardTitleId", SqlDbType.Int).Value = title.AwardTitleId;

        //-------------
        //This is the part that actually answers your question
        foreach (var p in cmd.Parameters.Where(p => p.Value == null))
        {
            p.Value = DBNull.Value;
        }
        //-------------

        cn.Open();
        cmd.ExecuteScalar();
    }
}

答案 1 :(得分:1)

嗯,使用您拥有的代码,您可以在SQL代码中使用null

description = "null";

但是,您应该使用参数化查询,而不是将值连接到SQL代码中。如果任何数据来自用户输入,则您的代码对SQL注入攻击持开放态度。

对于参数值,您使用DBNull.Value作为空值,因此保存它的变量必须是对象:

object description;

if (title.Description != null) {
  description = title.Description;
} else {
  description = DBNull.Value; 
}

现在,您可以在SqlParameter对象中使用该值。

答案 2 :(得分:1)

好的,首先要做的事情。您的代码要求SQL注入攻击。使用parameterized queries

解决问题本身。如果您想要的是数据库NULL,则需要传递值DBNull.Value。您可以使用字符串转换为适当值的辅助函数。

private object ConvertToDbReadyString(string value)
{
    if(value=="NULL")
        return DBNull.Value;
    else
        return value;
}

答案 3 :(得分:0)

if (title.Description != null)
      {
        description = "'" + title.Description + "'";
      }
      else
      {
        //here's where description should be a DBNULL. 
      }

试试这个:

description = title.Description ?? string.Empty;

答案 4 :(得分:0)

string variableValue == string.IsNullOrEmpty(stringValue) ? null : "Hello";
相关问题