【问题标题】:check the manual that corresponds to you mysql server version for the right syntax to use near '(CourseId = 'mect211')检查与您的 mysql 服务器版本相对应的手册,以获取在 '(CourseId = 'mect211') 附近使用的正确语法
【发布时间】:2014-08-01 20:28:25
【问题描述】:

我正在使用 MySql 在 C# 上编写一个学生数据库程序。我想更新信息,但它总是给我那个错误。这是我写的程序。

private void Update_bttn_Click(object sender, EventArgs e)
{
    string ConString = " datasource = localhost; port = 3306; username = root; password = 3306";
    string Query = " Update studentdata.studentrecord set (CourseId = '" + this.crsId.Text + "', CourseName = '" + this.crsName.Text + "',Credits = '" + this.credits.Text + "', CourseStatement = '" + this.CrseStatment.Text + "',Grade = '" + this.Grades.Text + "' where CourseId = '" + this.crsId.Text+"' ; ";
    MySqlConnection ConDatabase = new MySqlConnection(ConString);
    MySqlCommand cmdDataBase = new MySqlCommand(Query, ConDatabase);
    MySqlDataReader myReader;

    try
    {
        ConDatabase.Open();
        myReader = cmdDataBase.ExecuteReader();
        MessageBox.Show("Information Updated");
        while ((myReader.Read())) { }
        ConDatabase.Close();
    }
    catch (Exception ex) { MessageBox.Show(ex.Message); }
}

【问题讨论】:

  • 您正在打开一个括号 (CourseId,但没有在代码中的任何位置关闭它。不要连接查询,使用参数。您当前的代码容易发生 SQL 注入。
  • @Habib,这就是答案。
  • 我已经放了 )" 但仍然是相同的输出:还有其他建议吗?
  • 在执行之前使用调试器获取Querry 的实际值。获取它的值并尝试直接对您的数据库执行该命令。那至少应该给你一个更详细的错误

标签: c# mysql syntax-error


【解决方案1】:

为了以后参考,你可以通过调试获取query的值,并尝试在SQL中运行实际查询以获得更精确的错误。但是,在这种情况下,这是因为您在字符串后面有一个左括号 (CourseId... 并且没有关闭 )

此外,您可能想了解一些 documentation 与您在 C# 中使用 Sql 类相关的内容

【讨论】:

    【解决方案2】:

    使用参数化查询避免SQL注入

    How does SQLParameter prevent SQL Injection?

    你在CourseId附近有(

    string query = update studentdata.studentrecord set CourseId =@CourseId,CourseName=@CourseName,Credits =@Credits,CourseStatement=@CourseStatement,Grade =@Grade  where CourseId =@CourseId";
    
    MySqlConnection ConDatabase = new MySqlConnection(ConString);
    
    MySqlCommand cmdDataBase = new MySqlCommand(query, ConDatabase);
    
    cmdDataBase.Parameters.AddWithValue("@CourseId",this.crsId.Text );
    cmdDataBase.Parameters.AddWithValue("@CourseName", this.crsName.Text);
    

    等等

    【讨论】:

    • 嘿,谢谢!当我使用你的代码时,编译器告诉我:“在命令执行期间遇到致命错误。”有什么帮助吗?
    • 您必须以这种方式添加其他值,例如 CourseStatement
    • 我没明白你的意思...请给我解释一下
    猜你喜欢
    • 2020-02-09
    • 1970-01-01
    • 2016-08-06
    • 2012-05-02
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多