【问题标题】:Why do I get "You have an error in your SQL Syntax" when I pass parameters into MySqlParameter?当我将参数传递给 Sql 参数时,为什么会出现“您的 SQL 语法有错误”?
【发布时间】:2011-06-18 12:34:35
【问题描述】:

我的代码出现以下异常

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''MachineSimulator'' 

var sqlParams = new[]
                                            {
                                                new MySqlParameter("@MachineSimulatorDb",GlobalVariables.MachineSimulatorDb),
                                                new MySqlParameter("@CAMXMassagesTable" ,GlobalVariables.CamxmassagesTable)
                                            };

            using (var conn = new MySqlConnection(GlobalVariables.ConnectionString))
            {
                conn.Open();
                using(var command = new MySqlCommand())
                {
                    command.Connection = conn;
                    command.Parameters.AddRange(sqlParams);

                    command.CommandText = "CREATE DATABASE IF NOT EXISTS @MachineSimulatorDb;";

                    command.ExecuteNonQuery();


                }


            }

知道那里出了什么问题吗?

谢谢

【问题讨论】:

    标签: c# .net mysql sql


    【解决方案1】:

    MySQL 可能不允许您将参数传递给create database。试试:

    command.CommandText = string.Format("CREATE DATABASE IF NOT EXISTS `{0}`",  
        GlobalVariables.MachineSimulatorDb);
    

    如果您使用的变量来自 usafe 来源,您应该意识到 SQL 注入的危险。

    【讨论】:

    • ",如果我尝试使用 @MachineSimulatorDb;";我也有同样的例外。所以这不是他的问题。
    • @Night Walker:更可能的是,use 也不允许使用参数。通常,值允许使用参数,而不是指定数据库对象。所以where id = @MyParameter 会起作用,但select * from @MyTable 不会。
    【解决方案2】:

    当我使用 MySqlParameter 时,它使用的是 ?字符,而不是 @ 字符。这可能是您的问题;例如:

    new MySqlParameter("?MachineSimulatorDb");
    

    但 Andomar 可能是正确的,您不能使用 MySqlParameter 来提供新数据库的名称。

    【讨论】:

      猜你喜欢
      • 2017-07-14
      • 1970-01-01
      • 2011-03-14
      • 2012-02-06
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多