Add List<int> to a mysql parameter

when i pass it to the MySqlParameter and this is recognized as a string, it puts in the sql query like "1\,2\,3\,4" and this do not return the expected values.

I ran into this last night. I found that FIND_IN_SET works here:

SELECT * FROM table WHERE FIND_IN_SET(id, @parameter) != 0
...
intArray = new List<int>(){1,2,3,4};
conn.Command.Parameters.AddWithValue("parameter", string.Join(",", intArray));

Apparently this has some length limitations (I found your post looking for an alternate solution), but this may work for you.


Parameters don't work with IN. I have always embedded such things as a string in the query itself. While that is generally considered bad form because SQL injection, if you are constructing the query from a strongly typed numeric list, then there should be no possibility of any external input corrupting it in a meaningful way.


you are going to have to iterate over your array and create the list yourself

// no parameters
var sb = new StringBuilder();
for(int i=0;i<intArray.Length;i++)
{
    sb.Append(intArray[i] + ",");// no SQL injection they are numbers
}
if (sb.Length>0) {sb.Length-=1;}
string sql = "SELECT * FROM table WHERE id IN (" + sb.ToString() + ")";

UPDATE: Having thought more about this I'll go back to my original answer (below) which is to use parameters. Optimisations of built queries and whatever the database engine can muster are up to you.

// no parameters
var sb = new StringBuilder();
for(int i=0;i<intArray.Length;i++)
{
    sb.AppendFormat("p{0},", i);// no SQL injection they are numbers
    connection.Command.Parameters.AddWithValue("p"+i, intArray[i]);
}
if (sb.Length>0) {sb.Length-=1;}
string sql = "SELECT * FROM table WHERE id IN (" + sb.ToString() + ")";