【问题标题】:Generating MySQLCommand Strings生成 MySQLCommand 字符串
【发布时间】:2016-05-24 18:37:37
【问题描述】:

是否有正确的方法来生成有效的 MySQL 字符串,然后通过 MySqlCommand 传递值?

我目前使用这样的方法,如果我需要搜索更多列,我只会堆叠越来越多的条件。它看起来太恶心了,我认为有更好的方法来完成同样的事情。

private static string SelectUser(User u)
{
    bool and = false;
    string cmd = "SELECT * FROM `database`.`users` WHERE ";

    if (u.ID != null)
    {
        cmd += "`UserID` LIKE @0";
        and = true;
    }
    if (u.Username != null)
    {
        if (and) { cmd += " AND "; }
        cmd += "`Username` LIKE @1";
        and = true;
    }
    if (u.Role != null)
    {
        if (and) { cmd += " AND "; }
        cmd += "`Role` LIKE @1";
        and = true;
    }
    if (u.Department != null)
    {
        if (and) { cmd += " AND "; }
        cmd += "`Departments` LIKE @1";
        and = true;
    }
    if (u.Template != null)
    {
        if (and) { cmd += " AND "; }
        cmd += "`Template` LIKE @1";
        and = true;
    }

    return cmd;
}

我找到了一些几乎可以工作的方法,例如 this answer,但它们都不允许我通过 MySqlCommand.Parameters 模块化传递值。

【问题讨论】:

    标签: c# mysql


    【解决方案1】:

    有几件事可以尝试。

    首先,这样做:

       const string baseQuery = "SELECT * from database WHERE 1=1 AND ";
    

    那就做吧

       var andClauses = new List<string>();
       if (U.id != null)  andClauses.Add("UserID = @0");
       if (U.username != null)  andClauses.Add("Username = @1");
       /* more like this */
       var query = baseQuery + string.Join (" AND ", andClauses);
    

    这将在您的查询中为您提供一组串联的 AND。它看起来比你的问题更干净。

    另一个需要考虑的技巧:这样写你的查询

    const string baseQuery = @"
         SELECT whatever
           FROM mytable
          WHERE (userid = @0 OR @0 <= 0)
            AND (username = @1 OR LENGTH(@1) <= 0)
            AND (department = @2 OR LENGTH(@department) <= 0) ";
    

    这些(column = @val OR @val &lt;= 0) WHERE 子句允许您输入一个空字符串或一个零整数以有效地跳过该子句。

    string = @"value"; 构造让您可以在 C# 中编写多行字符串 - 非常方便地格式化您的查询,以便您有机会阅读它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2015-07-14
      • 1970-01-01
      相关资源
      最近更新 更多