C# 参数化查询';(@lastName-nvarchar(4000)、@firstName-nvarchar(4000)、@middleName';需要未提供的参数';@lastName';)
发生此异常是因为从C# 参数化查询';(@lastName-nvarchar(4000)、@firstName-nvarchar(4000)、@middleName';需要未提供的参数';@lastName';),c#,sql-server,datagridview,C#,Sql Server,Datagridview,发生此异常是因为从行单元格[“dglastname”]中提取的@lastName的值为null,因此SqlParameter的值必须设置为DBNull.value 解决此问题的一种方法是按如下方式替换参数初始化: foreach (DataGridViewRow row in dg1.Rows) { string constring = @"Data Source=localhost;Initial Catalog=RecruitmentDB;User ID=sa"; using
行单元格[“dglastname”]中提取的@lastName
的值为null
,因此SqlParameter
的值必须设置为DBNull.value
解决此问题的一种方法是按如下方式替换参数初始化:
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();
}
}
}
您不能像这样将参数传递给sql命令“您需要使用存储过程。如何在sql中创建存储过程以处理插入逻辑。然后,在创建SqlCommand时,设置CommandType=CommandType.StoredProcedure。然后,不要像您这样在命令文本中键入sql,您将指定存储过程。不过,我没有意识到您实际上可以通过这种方式将参数传递给sql查询。如何删除最后一行?它会添加到我的数据库中
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);