Mysql传递参数给出不同的结果

时间:2019-03-14 17:13:58

标签: c# mysql asp.net asp.net-core

我有ASP.NET Core网站,并且正在使用以下命令从数据库加载一些产品:

using (MySqlCommand cmd = new MySqlCommand("SELECT ROBAID, KATBR, NAZIV,
                            SLIKA FROM ROBA WHERE PODGRUPAID IN (@PG)", con))
{
    cmd.Parameters.AddWithValue("@PG", "PODGRUPAID");

    // Other reading code
}

问题是这样,我只得到前2个结果(检查器内部的MySqlDataReader内部),但是当我将命令字符串更改为SELECT ROBAID, KATBR, NAZIV, SLIKA FROM ROBA WHERE PODGRUPAID IN (PODGRUPAID)而不通过命令添加参数时,我得到了所有结果...

2 个答案:

答案 0 :(得分:0)

PODGRUPAID的值是什么? PODGRUPAID是否类似于“ A,B,C”?如果是这样,该命令将更像from django.db import models class Invitation(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) shifter = models.ForeignKey(User, on_delete=models.CASCADE) (作为一个完整的字符串)工作。您可以尝试Using comma separated value parameter strings in SQL IN clauses

答案 1 :(得分:0)

实际上,您在此参数值定义中将PODGRUPAID作为字符串传递:

cmd.Parameters.AddWithValue("@PG", "PODGRUPAID");

这将只选择具有特定值PODGRUPAID的值,而我发现您不能像这样简单地向IN子句添加参数。如果要包含多个值,可以使用FIND_IN_SET代替IN子句:

string podGrupAIDs = "value1,value2,...";

using (MySqlCommand cmd = new MySqlCommand(@"SELECT ROBAID, KATBR, NAZIV,
                            SLIKA FROM ROBA WHERE FIND_IN_SET(PODGRUPAID, @PG)", con))
{
    cmd.Parameters.AddWithValue("@PG", podGrupAIDs);

    // Other reading code
}

如果值来自数组或List<T>T =任何值类型),则可以在使用string.Join()之前将它们与FIND_IN_SET连接起来:

List<string> values = new List<string>() { "value1", "value2", ... };

using (MySqlCommand cmd = new MySqlCommand(@"SELECT ROBAID, KATBR, NAZIV,
                            SLIKA FROM ROBA WHERE FIND_IN_SET(PODGRUPAID, @PG)", con))
{
    cmd.Parameters.AddWithValue("@PG", string.Join(",", values));

    // Other reading code
}