【问题标题】:C# SQL parameterized SQL QueryC# SQL 参数化 SQL 查询
【发布时间】:2018-09-30 08:15:18
【问题描述】:

当我使用参数化 sql 查询时,我只是不断收到语法错误。

public List<string> Cat(string product,string table)
{
    List<string> Products = new List<string>();
    Global global = new Global();
    string sql = "SELECT @prod FROM @tbl";
    MySqlConnection connection = new MySqlConnection(global.ConnectionString);
    MySqlCommand command = new MySqlCommand(sql, connection);
    command.Parameters.AddWithValue("@prod", product);
    command.Parameters.AddWithValue("@tbl", table);
    connection.Open();
    MySqlDataReader reader = command.ExecuteReader();
    if (reader.HasRows)
    {
        while (reader.Read())
            Products.Add(reader.GetString("@prod"));
    }
    connection.Close();
    return Products;
}

public List<string> CallProducts(string category)
{
    string table;
    string product;
    List<string> stacks = new List<string>();
    if (category == "Accessories")
    {
        product = "Accessories_Name";
        table = "tbl_accessories";
        stacks.AddRange(Cat(product, table).ToArray());                
    }
    else if (category == "Batteries")
    {
        table = "tbl_batteries";
    }
    else if (category == "Cotton")
    {
        table = "tbl_cotton";
    }
    else if (category == "Juices")
    {
        table = "tbl_juices";
    }
    else if (category == "Kits")
    {
        table = "tbl_kits";
    }
    else if (category == "Mods")
    {
        table = "tbl_mods";
    }
    else
    {
        table = "tbl_vapeset";
    }
    return stacks;
}

我只是不断收到 SQL 语法错误。如果手动输入表格和名称而不是使用参数,则它可以工作。

希望您能提供帮助。

需要一个项目。

谢谢!

【问题讨论】:

  • 专业提示我们看不到您的屏幕,因此必须将错误复制进去
  • 还有public List&lt;string&gt; Cat(string product, string table)
  • 您好专业提示,您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“tbl_accessories”附近使用正确的语法。
  • 这是我得到的错误。

标签: c# mysql


【解决方案1】:

正确的用法是:

string sql = $"SELECT {product} FROM {table}";

因为表和列不是参数。

此外,我建议使用Command.Parameters.Add(...).Value(...), 在Parameters.AddWithValue 上,因为在第一种方法中,您可以明确决定要传递的数据类型并防止 SQL 猜测它。

【讨论】:

  • 嗨,我试过用这个但也给出了同样的错误。您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“} FROM {table}”附近使用正确的语法
  • 嘿,谢谢你的提示 :) 帮了大忙 :) 我们现在明白了
  • 如果回答对您有帮助,您应该接受它(左侧的绿色复选标记)并可选择投票。
猜你喜欢
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多