在創建實際對象之前,有沒有辦法爲MySQLCommand
對象創建參數?添加MySQL參數
目前我有設置生成的命令是這樣的:
public static MySqlCommand User(MySqlConnection MySQL, User u)
{
var cmdVars = new List<string>();
const string cmd = "SELECT * FROM `schema`.`table` WHERE 1=1 AND ";
if (u.ID != null) cmdVars.Add("`ID` LIKE @0");
if (u.Username != null) cmdVars.Add("`Username` LIKE @1");
if (u.First != null) cmdVars.Add("`FirstName` LIKE @2");
if (u.Last != null) cmdVars.Add("`LastName` LIKE @3");
if (u.Phone != null) cmdVars.Add("`Phone` LIKE @4");
if (u.Extension != null) cmdVars.Add("`Extension` LIKE @5");
if (u.Email != null) cmdVars.Add("`Email` LIKE @6");
var MySqlCmd = new MySqlCommand(cmd + string.Join(" AND ", cmdVars), MySQL);
if (u.ID != null) MySqlCmd.Parameters.AddWithValue("@0", u.ID);
if (u.Username != null) MySqlCmd.Parameters.AddWithValue("@1", u.Username);
if (u.First != null) MySqlCmd.Parameters.AddWithValue("@2", u.First);
if (u.Last != null) MySqlCmd.Parameters.AddWithValue("@3", u.Last);
if (u.Phone != null) MySqlCmd.Parameters.AddWithValue("@4", u.Phone);
if (u.Extension != null) MySqlCmd.Parameters.AddWithValue("@5", u.Extension);
if (u.Email != null) MySqlCmd.Parameters.AddWithValue("@6", u.Email);
return MySqlCmd;
}
其中,雖然做工精細,是毛看會陸續添加更多的參數,並要求用戶創建一個新的用戶對象只是搜索一個值。
我認爲切換到in this question所示的方法,但與MySQLConnector配合使用時,管理這些值變得過於複雜,並且沒有爲提高可讀性做任何事情。
除了有'schema'.'table''和'」之間的區別schema'.'table'' – MethodMan
@MethodMan我不確定你想說什麼。 – Uueerdo
我仍然不確定你的意思。在我發佈的任何地方都沒有單引號,「'」是MySQL用來包含模式,表和字段名的東西。 (_「弄明白」_使它看起來像你正在拖曳,並且實際上不能指出問題。) – Uueerdo