【问题标题】:MySqlException was unhandled during insert [closed]插入期间未处理 MySqlException [关闭]
【发布时间】:2014-04-30 03:13:08
【问题描述】:

我正在使用 MySql 创建一个 Visual Studios 注册表单,但我不断收到错误消息:

命令执行过程中遇到致命错误

知道是什么原因造成的吗?

MySqlConnection connection;
string cs = @"server=127.0.0.1;userid=root;password=welcome;database=userinfo";
connection = new MySqlConnection(cs);
connection.Open();

MySqlCommand command = new MySqlCommand();
string SQL = "INSERT INTO `users` (`userid`, `email`, `passone`, `passtwo`,'lastname','firstname') VALUES (@userid_txt, @email_txt, @passone_txt, @passtwo_txt, @lastname_txt, @firstname_txt)";
command.CommandText = SQL;
command.Parameters.AddWithValue("userid", userid_txt);
command.Parameters.AddWithValue("email", email_txt);
command.Parameters.AddWithValue("passone", passone_txt);
command.Parameters.AddWithValue("passtwo", passtwo_txt);
command.Parameters.AddWithValue("lastname", lastname_txt);
command.Parameters.AddWithValue("firstname", firstname_txt);
command.Connection = connection;

command.ExecuteNonQuery();

connection.Close();

内部异常状态:

必须定义参数“@userid_txt”

【问题讨论】:

  • 阅读(并报告)完整错误消息。
  • 在查看详细信息和 InnerException 选项卡下显示“必须定义参数'@userid_txt'”
  • 那么问题来了!现在,仔细阅读错误消息,并查看使用的参数名称
  • 调整了值以包含“@”符号以及同样的致命错误消息
  • 是的,感谢您帮助指出我所缺少的内容

标签: c# mysql ado.net


【解决方案1】:

在以下语句中使用参数时:

 .. VALUES (@param1, @param2, ...

应该有对应的Parameters。 AddXXX() 匹配参数文本的行,例如:

command.Parameters.AddWithValue("param1", somevalue);
command.Parameters.AddWithValue("param2", othervalue);

在您的情况下,您的参数标签不匹配:

 .. VALUES (@userid_txt, @email_txt, ...

其中“userid_txt”需要在Parameters集合中指定:

command.Parameters.AddWithValue("userid_txt", userid_txt);

您有“userid”而不是“userid_txt”。其他参数也一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多