0

I want to reuse a parameterized query in a loop.

(This query is a simple example, I don't think I could make the loop inside sql and just return the needed rows)

Instead of

private String sql = "SELECT v FROM t WHERE VAL_1 = @param_1";
for (int n=1;n<10;n++)
{
    MySqlCommand m = new MySqlCommand(sql);
    m.Parameters.AddWithValue("@param_1", n);
    res = Convert.ToInt32(m.ExecuteScalar());
    ( ... )
}

I'd like to move the setup of the query outside the loop; something like

private String sql = "SELECT v FROM t WHERE VAL_1 = @param_1";
MySqlCommand m = new MySqlCommand(sql);
m.Parameters.Add("@param_1");  // does not exist
for (int n=1;n<10;n++)
{
    m.Parameters.Set("@param_1", n); // does not exist
    res = Convert.ToInt32(m.ExecuteScalar());
    ( ... )
}

So the server does not have to parse the same sql for each ilteration in loop.

Is that possible?

2
  • Have you want to assign parameter values inside the loop? Note that the loop itself may override previous assignments for corresponding parameter, ensure every assignment executed before the loop going to next iteration. Commented May 31, 2017 at 12:00
  • do you mean you want to pass a different parameter at every step in the for loop? Commented May 31, 2017 at 12:02

4 Answers 4

7

You can add a parameter with

m.Parameters.Add("@param_1", MySqlDbType.Int32);

and later in the loop assign a value with

m.Parameters["@param_1"].Value = n;
Sign up to request clarification or add additional context in comments.

Comments

2

If you just need to run query for list of parms without do diffrent things on each result, You can create a string with a loop like that:

String  where_str= VAL_1 = @param_1" OR VAL_1 = @param_2" OR VAL_1 = @param_3"...

String sql = "SELECT v FROM t WHERE " + where_str;

and then exec the query it will give the same result.

If you need to saparate results so you can make it with prepaerd statement. Also, I recommend you to read about stored procedure it may be the best soultion for you in some cases.

example for prepaerd statement: (more info in the link)

private static void SqlCommandPrepareEx(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand(null, connection);

        // Create and prepare an SQL statement.
        command.CommandText =
            "INSERT INTO Region (RegionID, RegionDescription) " +
            "VALUES (@id, @desc)";
        SqlParameter idParam = new SqlParameter("@id", SqlDbType.Int, 0);
        SqlParameter descParam = 
            new SqlParameter("@desc", SqlDbType.Text, 100);
        idParam.Value = 20;
        descParam.Value = "First Region";
        command.Parameters.Add(idParam);
        command.Parameters.Add(descParam);

        // Call Prepare after setting the Commandtext and Parameters.
        command.Prepare();
        command.ExecuteNonQuery();

        // Change parameter values and call ExecuteNonQuery.
        command.Parameters[0].Value = 21;
        command.Parameters[1].Value = "Second Region";
        command.ExecuteNonQuery();
    }
}

3 Comments

I specified I could not do one query and loop over the result, the query was a simple example.
Did you try to do something like the example of the prepared statement i wrote?
Yeah; I didn't notice the change of parameters, because I saw no loop. Sorry; I can't un-downvote your answer.
1

Yes, this should be possible! Have a look for SQL Prepared Statements!

You can just use:

cmd = new MySqlCommand("SELECT * FROM yourTable WHERE condition=@val1", MySqlConn.conn);

In the loop add the parameters and prepare the command

cmd.Parameters.AddWithValue("@val1", value);
cmd.Prepare();

after the loop execute your query with

cmd.ExecuteNonQuery();

2 Comments

I specified I could not do one query and loop over the result, the query was a simple example.
@LeifNeland: I strongly believe that you can't do like this doesn't be a reason for a down vote
0

Yep, you can do all of those things but unless that's just an example you'd want to use IN with all the values or a join to a bulk loaded temp table if there are a large number of them. The reason is that each round trip to the DB has a significant overhead that you can reduce from n to 1 with either of those techniques.

4 Comments

I specified I could not do one query and loop over the result, the query was a simple example.
Sure you can. If you can write it as a loop you can write it as a set. Maybe you should ask the question you want answered rather than make assumptions and then down vote people trying to help.
Sorry. I dumbed down the example too much, to get the answer on the real problem instead of the example. Instead of using a series of queries to the database, I should just fetch the entire database to an array and search that instead. Yeah, right.
What?! You clearly don't understand how databases work or how to use them to the full potential. Never mind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.