Invalid Cast Exception was unHandled MySQL

前端 未结 2 710
自闭症患者
自闭症患者 2021-01-23 05:24

When I run the program I get this error:

Invalid Cast Exception was unHandled

This is part of form for fill a database, and visual

相关标签:
2条回答
  • 2021-01-23 05:56

    The problem is the ExecuteScalar that in MySql returns an Int64 not an Int32. So the invalid cast when you use an explicit cast

    With a conversion your error should go away

     int UsuarioExiste = Convert.ToInt32(sqlCommand.ExecuteScalar());
    

    You are not alone to fall in this problem

    Of course everything that has been said in the answer from Mr Soner Gönül is still applicable and should be done ASAP.

    0 讨论(0)
  • 2021-01-23 06:08

    I strongly suspect, you parameterize your LIKE part in a wrong way. You need to use %..% at least to figure out you try to get values that includes those string. Like;

    sqlCommand.Parameters.AddWithValue("@pNombre", "%" + txtNombre.Text + "%");
    sqlCommand.Parameters.AddWithValue("@pApellido", "%" + txtApellido.Text + "%");
    

    Don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.

    Also use using statement to dispose your connection and command automatically instead of calling (in somewhere maybe in your code) Close or Dispose methods manually.

    By the way, be aware, COUNT(*) returns BIGINT in MySQL and this type mapped with Int64 in .NET side. As Steve mentioned, you can parse this value instead of casting like;

    int UsuarioExiste = int.Parse(sqlCommand.ExecuteScalar());
    

    or you can define your UsuarioExiste as long which seems more consistent(?) I think.

    long UsuarioExiste = (long)sqlCommand.ExecuteScalar();
    
    0 讨论(0)
提交回复
热议问题