2016-06-30 64 views
-1

在創建實際對象之前,有沒有辦法爲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配合使用時,管理這些值變得過於複雜,並且沒有爲提高可讀性做任何事情。

回答

0

如何使用這樣

... WHERE (@0 is null or `ID` LIKE @0) 
     AND (@1 is null or `Username` LIKE @1) 
     AND (@2 is null or `FirstName` LIKE @2) ... 

查詢然後你就可以添加所有參數,不管NULL與否。

之前執行就可以運行這個

private void FillNullValuesWithDbNull(SqlParameterCollection parameters) 
{ 
    foreach (IDataParameter param in parameters) 
    { 
     if (param.Value == null) param.Value = DBNull.Value; 
    } 
} 
0

我的建議是,而不是有User實例傳遞給函數,創建一個名爲像UserSearchCriteria新類;該類可以有一個更簡單的設計(0參數構造函數,具有簡單setter的所有屬性等)。

縮短或「清理」功能代碼並沒有多大作用,但會使功能更簡單。


其實,只要功能的話,你也許可以做這樣的事情......

public static MySqlCommand User(MySqlConnection MySQL, UserSearchCriteria u) 
{ 
    var cmdVars = new List<string>(); 
    const string cmd = "SELECT * FROM `schema`.`table` WHERE 1=1 AND "; 

    var MySqlCmd = new MySqlCommand("", MySQL); 

    if (u.ID != null) 
    { 
     cmdVars.Add("`ID` LIKE @0"); 
     MySqlCmd.Parameters.AddWithValue("@0", u.ID); 
    } 
    if (u.Username != null) 
    { 
     cmdVars.Add("`Username` LIKE @1"); 
     MySqlCmd.Parameters.AddWithValue("@1", u.Username); 
    } 

    // and the rest of the relevant properties 

    MySqlCmd.CommandText = cmd + string.Join(" AND ", cmdVars); 

    return MySqlCmd; 
} 

public void somefunction() 
{ 
    var myCmd = User(someconnections, new UserSearchCriteria() {FirstName = "Joe"}); 
} 
+0

除了有'schema'.'table''和'」之間的區別schema'.'table'' – MethodMan

+0

@MethodMan我不確定你想說什麼。 – Uueerdo

+0

我仍然不確定你的意思。在我發佈的任何地方都沒有單引號,「'」是MySQL用來包含模式,表和字段名的東西。 (_「弄明白」_使它看起來像你正在拖曳,並且實際上不能指出問題。) – Uueerdo