Add List to a mysql parameter

后端 未结 9 1322
暗喜
暗喜 2020-12-14 02:36

I have this question about the MySqlParameter from the .NET connector.

I have this query:

SELECT * FROM table WHERE id IN (@parameter)
9条回答
  •  别那么骄傲
    2020-12-14 03:03

    I don't think there's a way you can add them like that, but perhaps you could iterate through the list and generate the query dynamically.

    For example:

    var intArray = new List(){1,2,3,4};
    if (intArray.Count > 0) {
        var query = "SELECT * FROM table WHERE id IN (";
        for (int i = 0; i < intArray.Count; i++) {
            //Append the parameter to the query
            //Note: I'm not sure if mysql uses "@" but you can replace this if needed
            query += "@num" + i + ",";
            //Add the value to the parameters collection
            ...connection.Command.Parameters.AddWithValue("num" + i, intArray[i]);
        }
        //Remove the last comma and add the closing bracket
        query = query.Substring(0, query.Length - 1) + ");";
        //Execute the query here
    }
    

    This way, you could even use a differently typed list and still reap the benefits of parameterized queries. However, I don't know if there would be performance issues with larger lists but I suspect that would be the case.

提交回复
热议问题