将空值插入SQL Server中的int列

时间:2018-07-04 13:46:50

标签: c# asp.net

public bool insertRowIntoApplicant(int AnsId, string Name)
{
    string CS = Utilities.GetConnString();

    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand("Insert Into ApplicantTable (AnswerableId, Name) values (@AnsId, @Name);

        SqlParameter paraAnsId = new SqlParameter()
                    {
                        ParameterName ="@AnsId",
                        SqlDbType = System.Data.SqlDbType.Int,
                        Direction = System.Data.ParameterDirection.Input,
                        Value = AnsId
                    };
        cmd.Parameters.Add(paraAnsId);
        cmd.Parameters.Add(paraName);
    }
}

我从隐藏字段中获取值

int getAnswerabelValue = Convert.ToInt32(hfAnswerableID.Value);

if (dal_Obj1.insertRowIntoApplicant(getAnswerabelValue, Name)
{
}

我的问题是getAnswerabelValue有时可以为null,那么如何更改我的代码?

2 个答案:

答案 0 :(得分:6)

该列可以为空吗?然后,变量也应为Nullable<int>

int? ansIdOrNull = null;
int ansId;
if(int.TryParse(hfAnswerableID.Value, out ansId))
    ansIdOrNull = ansId;

// pass ansIdOrNull to the method...

如果是DBNull.Value,则必须使用null

public bool insertRowIntoApplicant(int? ansId, string Name)
{
    string CS = Utilities.GetConnString();
    using (SqlConnection con = new SqlConnection(CS))
    {
       SqlCommand cmd = new SqlCommand("Insert Into ApplicantTable(AnswerableId,Name) values(@AnsId,@Name);
       SqlParameter paraAnsId = new SqlParameter()
        {
            ParameterName ="@AnsId",
            SqlDbType = System.Data.SqlDbType.Int,
            Direction = System.Data.ParameterDirection.Input,
            Value = (object)ansId ?? DBNull.Value
        };
        // initialize paraName
        cmd.Parameters.Add(paraAnsId);
        cmd.Parameters.Add(paraName);
    }
}

答案 1 :(得分:0)

如果您的db列接受null,那么您将需要声明int为可为null的int

int? getAnswerabelValue = hfAnswerableID;