【问题标题】:Unknown column '' in 'where clause' c#'where子句'c#中的未知列''
【发布时间】:2014-02-04 15:42:05
【问题描述】:

我尝试在两个条件下进行 Select。 这是我的功能:

public static List<T> Select_mult(List<string> list, string op)
    {
        List<T> liste = new List<T>();
        using (MySqlConnection connexion = new MySqlConnection("Data Source=localhost;Initial Catalog=dev_ing2;User Id=root ;Password='';"))
        {
            Type type = typeof(T);
            connexion.Open();
            MySqlTransaction transaction = connexion.BeginTransaction();
            string req = "SELECT * FROM " + type.Name + " WHERE (";
            MySqlCommand command = new MySqlCommand();
            foreach (PropertyInfo p in type.GetProperties())
            {
                if (p.Name == "Id")
                    break;                  
                foreach (string value in list)
                {
                    req += p.Name.ToLower() + " = ";
                    req += value + " OR ";
                }
                req = req.Substring(0, req.Length - 3);
                req += ")" + op +"(" ;
            }
            req = req.Substring(0, req.Length - 5);
            Console.WriteLine(req);
            Console.ReadLine();
            command.Connection = connexion;
            command.Transaction = transaction;
            command.CommandText = req;
            MySqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                T user = new T();
                foreach (PropertyInfo p in type.GetProperties())
                {
                    p.SetValue(user, reader[p.Name]);
                }
                liste.Add(user);
            }
        }
        return liste;
    }
}

我在“where 子句”中有一个错误未知列“Chassot”。 “Chassot”是我的 sql 表中用户的姓氏

感谢帮助。 =)

【问题讨论】:

  • 检查列表中的值?
  • 发布 Console.WriteLine(req) 输出的内容
  • 我建议使用经过全面测试的 ORM,例如 Dapper
  • 是您在type.properties "chassot" 的物业之一?
  • 您的语法在 Where 子句中是关闭的。要么比,要么您尝试引用该实例中不存在的列。

标签: c# sql select


【解决方案1】:

如果一列是字符串类型,您应该将值括在引号中,我不认为您这样做。

您应该使用现有的 ORM 之一,而不是尝试自己编写。

【讨论】:

    【解决方案2】:

    乍一看,它看起来像这样:

    req += p.Name.ToLower() + " = ";
    req += value + " OR ";
    

    应该是这样的:

    req += p.Name.ToLower() + " = '";
    req += value + "' OR ";
    

    你没有用引号括起你的价值。至少这似乎是您期望的行为。请注意,当您尝试比较 varchar 以外的内容时,您可能会遇到问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 2021-09-19
      • 2020-06-28
      • 2021-07-02
      • 2019-08-14
      • 2013-07-18
      相关资源
      最近更新 更多