【发布时间】: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 模块化传递值。
【问题讨论】: