0

我试图将一些变量传递给参数化查询,但是当值为 NULL 时,它会引发一个异常,指出未提供该值。

如果没有 if 或类似的东西,我该如何解决这个问题?

我的代码是这个

var cmdPersona_Log = new SqlCommand();
cmdPersona_Log.Parameters.Clear();
cmdPersona_Log.Connection = mySqlConnection;
cmdPersona_Log.CommandType = CommandType.Text;
cmdPersona_Log.CommandText = @"INSERT INTO [Tomin].[TominRH].[Persona_Log] "
+ "([Id_Action],[Id_User],[Id_Date],[Id_Entidad],[Nombre],[Paterno],[Materno],[Sexo],[Id_Nacionalidad])"
+ " Values (1, 'Admin', @fecha, @id_entidad, @nombre, @paterno, @materno, 1, 52)";

cmdPersona_Log.Parameters.Add("@fecha", DateTime.Now);
cmdPersona_Log.Parameters.Add("@id_entidad", dbRow["CUENTA"]);
cmdPersona_Log.Parameters.Add("@nombre", nombre);
cmdPersona_Log.Parameters.Add("@paterno", paterno);
cmdPersona_Log.Parameters.Add("@materno", materno);

cmdPersona_Log.ExecuteNonQuery();
4

1 回答 1

3

I will assume that your problem is that the underlying field doesn't support nulls. If this is the case, you could do something like this

cmdPersona_Log.Parameters.Add("@nombre", nombre ?? string.Empty);
cmdPersona_Log.Parameters.Add("@paterno", paterno ?? string.Empty); 
cmdPersona_Log.Parameters.Add("@materno", materno ?? string.Empty);

You'll be inserting an empty string in case you have a null using the null-coalescing operator.

于 2012-08-28T00:24:39.613 回答