简体   繁体   English

查询参数化不能用c#和SQL Server插入值

[英]Query parameterized cannot insert value with c# and SQL Server

I have a parameterized query and it was working fine, but when I delete de DB and create it again, with the same values and everything, it throws an exception that says it cannot insert value NULL with the value sexo, but all the values are assigned, here it's the code: 我有一个参数化查询,它工作正常,但当我删除de DB并再次创建它,具有相同的值和所有内容时,它抛出一个异常,说它不能插入值为NULL的值为sexo,但所有的值都是已分配,这是代码:

    try{
      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, @sexo, 52)";
      cmdPersona_Log.Parameters.AddWithValue("@fecha", DateTime.Now);
      cmdPersona_Log.Parameters.AddWithValue("@id_entidad", dbRow["CUENTA"].ToString().Trim());
      cmdPersona_Log.Parameters.AddWithValue("@nombre", nombre ?? string.Empty);
      cmdPersona_Log.Parameters.AddWithValue("@paterno", paterno ?? string.Empty);
      cmdPersona_Log.Parameters.AddWithValue("@materno", materno ?? string.Empty);
      cmdPersona_Log.Parameters.AddWithValue("@sexo", 1);
      cmdPersona_Log.ExecuteNonQuery();
   }
   catch(Exception e) 
   {
      MessageBox.Show(dbRow["CUENTA"] + " Persona_log  " + e.ToString());
   } 

I've checked the DB and it doesn't seem to be the problem, any sugestion?? 我检查了数据库,它似乎没有问题,任何消化?

You may be running into a case where AddWithValue isn't inferring your parameter type of bit properly. 您可能遇到AddWithValue未正确推断您的参数类型bit Use true / false instead of 1 / 0 : 使用true / false的,而不是1 / 0

cmdPersona_Log.Parameters.AddWithValue("@sexo", true);

确保INSERT子句中列出了应该为非null的表的所有字段

您是否尝试过使用此表单cmd.Parameters.Add("@SomeID", SqlDbType.Int, 4).Value =您可以在哪里明确SqlDbType?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM