Using named parameters with the MySQL.NET provider

In the MySQL.NET provider, you can use named parameters in the syntax:

?parametername

      

Now I am trying to create a named parameter for the parameter to be used in the "IN" list for example.

select * from mytable where id in (?ids)

      

How can I use a named parameter with this, if I use varchar it will add quotes before and after the list, i.e .:

If I pass the parameter value using varchar:

cmd.Parameters.Add("?ids", MySqlDbType.Varchar).Value = ids; // ids is a string which contains the ids separated by commas, e.g. 1, 2, 3 .. etc

      

the request will be executed like this:

select * from mytable where id in ('1, 2 ,3')

      

Of course this will throw an error, how can I pass the named parameter without getting the quotes, this is how it should be done:

select * from mytable where id in (1, 2 , 3)

      

Is there a workaround for this? I am currently using String.Format () but would like to use a named parameter, is it possible like?

PS I only use simple text instructions, not sproc, so none of them will be passed to sproc (just in case you think this is not possible, because sprocs does not accept arrays)

+1


a source to share


2 answers


This has been asked here so many times that I stopped counting.

It is always the same answer, regardless of technology. You just have to add as parameters to your request, as you plan on using "arguments".

If you want to query WHERE id IN (1, 2 ,3)

, your prepared statement should look like this:

SELECT * FROM mytable WHERE id IN (?, ?, ?)

      



Use whatever string builder you think is appropriate for creating such a SQL string. Then add three parameter values ​​to it.

This is a whole point of prepared statements for separating SQL code from data. The commas are SQL code, you will never get them into a single parameter statement, they should come before.

Okay, there is one alternative. Create a separate / temporary table, store your ids in it and request something like this:

SELECT
  * 
FROM 
  mytable m
  INNER JOIN searchtable s ON m.id = s.id

      

+3


a source


The problem is that you are not passing just one parameter. You want to pass a collection of parameters. As far as I know, there is no support yet (no DbType for arrays or collections). Thus, you cannot add multiple values ​​to one parameter.

Since (I suppose) the numeric elements in 'ids' can vary, you will need to change the command line to have the correct number of parameters. It would be possible to use some ot loops to generate and command line and populate the parameters with appropriate values. This basically means that you create a new command for every request.



Another solution would be to use a stored procedure that takes your comma separated list and uses it to build your query.

+1


a source







All Articles