无效的强制转换异常是未处理的 MySQL
本文关键字:未处理 MySQL 异常 转换 无效 | 更新日期: 2023-09-27 18:32:04
当我运行程序时,出现此错误:
无效的强制转换异常未处理
这是用于填写数据库的表单的一部分,Visual Studio 将 int 强制转换标记为错误
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);
}
问题是 ExecuteScalar 在 MySql 中返回 Int64 而不是 Int32。因此,使用显式强制转换时无效的强制转换
通过转换,您的错误应该会消失
int UsuarioExiste = Convert.ToInt32(sqlCommand.ExecuteScalar());
你不是唯一一个陷入这个问题的人
当然,Soner Gönül先生在回答中所说的一切仍然适用,应该尽快完成。
我强烈怀疑,你以错误的方式参数化了你的LIKE
部分。您至少需要使用%..%
来确定您尝试获取包含这些字符串的值。喜欢;
sqlCommand.Parameters.AddWithValue("@pNombre", "%" + txtNombre.Text + "%");
sqlCommand.Parameters.AddWithValue("@pApellido", "%" + txtApellido.Text + "%");
不要尽可能多地使用AddWithValue
。它有时可能会产生意想不到和令人惊讶的结果。使用Add
方法重载指定参数类型及其大小。
还可以使用 using
语句自动释放连接和命令,而不是手动调用(在代码中的某个地方)Close
或Dispose
方法。
顺便说一下,请注意,COUNT(*)
在MySQL中返回BIGINT
,并且此类型与.NET端的Int64
映射。正如 Steve 提到的,您可以解析此值而不是强制转换 like;
int UsuarioExiste = int.Parse(sqlCommand.ExecuteScalar());
或者您可以将UsuarioExiste
定义为看起来更一致的long
(?我认为。
long UsuarioExiste = (long)sqlCommand.ExecuteScalar();