本文介绍了未处理的无效转换异常 MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行程序时出现此错误:

When I run the program I get this error:

未处理无效的投射异常

这是填充数据库表单的一部分,Visual Studio 将 int 类型转换标记为错误

This is part of form for fill a database, and visual Studio marks the int cast as the error

MySqlConnection conectar = new MySqlConnection("server=127.0.0.1; database=gymne; Uid=root; pwd=0000000000;");
using (MySqlCommand sqlCommand = new MySqlCommand("SELECT COUNT(*) from Socios where Nombre like @pNombre AND Apellido like @pApellido", conectar))
{
     conectar.Open();
     sqlCommand.Parameters.AddWithValue("@pNombre", txtNombre.Text);
     sqlCommand.Parameters.AddWithValue("@pApellido", txtApellido.Text);
     int UsuarioExiste = (int)sqlCommand.ExecuteScalar();//<----"error here"
     if (UsuarioExiste > 0)
     {
         MessageBox.Show("El Socio ya existe!!", "No Guardado", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }

推荐答案

强烈怀疑,您以错误的方式参数化了 LIKE 部分.您至少需要使用 %..% 来确定您尝试获取包含这些字符串的值.喜欢;

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 + "%");

尽量不要使用AddWithValue.可能 有时会产生意想不到的和令人惊讶的结果.使用 Add 方法重载来指定参数类型和大小.

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.

还使用 using 声明自动处理您的连接和命令,而不是手动调用(在您的代码中的某处)CloseDispose 方法.

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.

顺便说一句,请注意,COUNT(*) 返回 BIGINT 在 MySQL 中,此类型映射到 Int64 在 .NET 端.正如史蒂夫提到的,你可以解析这个值而不是像这样强制转换;

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());

或者您可以将您的 UsuarioExiste 定义为 long,我认为这看起来更一致(?).

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

long UsuarioExiste = (long)sqlCommand.ExecuteScalar();

这篇关于未处理的无效转换异常 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:08