参数化查询'(@ lastName nvarchar(4000),@ firstName nvarchar(4000),@ middleName'需要参数' @ lastName',这是未提供的

时间:2017-09-02 02:05:51

标签: c# sql-server datagridview

foreach (DataGridViewRow row in dg1.Rows)
{
    string constring = @"Data Source=localhost;Initial Catalog=RecruitmentDB;User ID=sa";
    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO ApplicantFamilyBackground(lastName,firstName,middleName,relationship,applicantcode) VALUES(@lastName, @firstName, @middleName, @relationship, @applicantcode)", con))
        {
            cmd.Parameters.AddWithValue("@lastName", row.Cells["dglastname"].Value);
            cmd.Parameters.AddWithValue("@firstName", row.Cells["dgfirstname"].Value);
            cmd.Parameters.AddWithValue("@middleName", row.Cells["dgmiddlename"].Value);
            cmd.Parameters.AddWithValue("@relationship", row.Cells["dgrelationship"].Value);
            cmd.Parameters.AddWithValue("@applicantcode",row.Cells["dgapplicantcode"].Value = lblapplicantcode.Text.ToString());

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

发生异常是因为从@lastName拉出的row.Cells["dglastname"].Value的值为null,因此SqlParameter的值必须设置为DBNull.Value }。

修复它的一种方法是更换参数初始化,如下所示:

cmd.Parameters.AddWithValue("@lastName", row.Cells["dglastname"].Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("@firstName", row.Cells["dgfirstname"].Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("@middleName", row.Cells["dgmiddlename"].Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("@relationship", row.Cells["dgrelationship"].Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("@applicantcode", row.Cells["dgapplicantcode"].Value = lblapplicantcode.Text != null ? lblapplicantcode.Text.ToString() : DBNull.Value);