I have this question about the MySqlParameter from the .NET connector.
I have this query:
SELECT * FROM table WHERE id IN (@parameter)
And the MySqlParameter is:
intArray = new List<int>(){1,2,3,4};
...connection.Command.Parameters.AddWithValue("parameter", intArray);
This is possible? Is possible to pass an array of int to a single MySqlParameter? The other solution will be convert the array of int to a string such like "1,2,3,4", but this, 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.
@ UPDATE: Seems like the mysql connector team should work a little bit harder.
I ran into this last night. I found that FIND_IN_SET works here:
Apparently this has some length limitations (I found your post looking for an alternate solution), but this may work for you.
you are going to have to iterate over your array and create the list yourself
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.
You have a few options here (in order of preference):
The data has to come from somewhere: either your database, user action, or machine-generated source.
If it's created by the user, add it to a separate table on each individual user action, and then use a sub query.
An example of this is a shopping cart. A user might select several items to purchase. Rather than keep these in the app and need to add all the items to an order in one go when they check out, add each item to a table in the db as the user selects or changes it.
The definitive (and I mean definitive) work on the subject is here:
http://www.sommarskog.se/arrays-in-sql.html
The article long, but in a good way. The author is a sql server expert, but the concepts on the whole apply to MySQL as well.
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:
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.
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.
As I know you cannot provide any array as a parameter to prepared statement. IN() doesn't support parameters as an array.