0

So, I am trying to using conditional statements and check boxes on a form in c# to conditionally build a MySQL SQL query. I don't see many topics on it so either I am doing something wrong (quite possible), or I am missing something simple. Either way, I have hit a wall and could use some help.

Here is the scenario: I am trying to make a search form in c# for my MySQL database, and depending upon which options the user selects depends on how granular the search is.

So basically it looks like this:

/*Obviously sanitized
  the variable areas*/
string exportQuery = "SELECT * FROM `/*Schema*/`.`/*Table*/` WHERE `/*PK*/`=";
List<string> parameters = new List<string>();
List<string> fields = new List<string>();
List<string> placeholders = new List<string>();
DataTable exportTemp;
int v = 0;

and at each point below that, it goes through a check like this:

 if (/*ACheckBox*/.Checked == true)
 {
     v++;
     /*String variable I initialized earlier*/ = DateTimePickerOnForm.Value.ToString("yyyy-MM-dd");
     parameters.Add(/*String variable I initialized earlier*/);
     fields.Add("AND `/*FieldX*/`=@/*FieldVar*/ ");
     placeholders.Add("@/*FieldVar*/");
 }

and at the end it counts them all up and starts adding:

 if (v > 0)
 {
     //Build the custom Query
     foreach (string s in fields)
     {
         exportQuery += s;
     }
     //tack on the closing semicolon
     exportQuery += ";";
     Program.conn.Open();
     using (MySqlCommand data = new MySqlCommand(exportQuery, Program.conn))
     {
         data.Prepare();
         for (int f = 0; f < v; f++)
         {
             data.Parameters.AddWithValue("\"" + placeholders[f] + "\"", parameters[f]);
         }
         //Datatable prep
         exportTemp = Program.FillTable(data);/*this runs the query through the database*/
      }

However, I am getting undefined variable errors back (e.g. "field1 must be defined"). Now some quick notes for clarification.

• Where its throwing the error is in the first variable added with the loop.

• All areas where I just put a comment are sanitized, but when its used again I repeat the comment name.

• If I shouldn't be using this method, I am open to other methods.

Edit: • the first parameter I am trying to pass is a string the snippet of a datetime area was chosen for its simplicity to demonstrate my methodology.

Any help is appreciated, obviously trying to sanitize my inputs, but I am not sure what I am doing wrong.

3
  • Using AddWithValue means the DB Engine has to guess at the real datatype. Given the nature of this thing, that means you will likely pass them as Object or string making it harder to guess correctly. I'd go back to the drawing board and avoid a general purpose method Commented Mar 4, 2018 at 21:15
  • @Plutonix I might be wrong, but although you are right, I think more precisely the parameters are passed in as boxed strings. Maybe having a List<Object> instead of List<string> for parameters would mean the parameters get passed in as boxed Objects of the data type they need to be, which would achieve OP's goals Commented Mar 4, 2018 at 21:23
  • @AlexC.Unfortunately that didn't do it. Plutonix might have been right, but I'm holding onto hope someone else may come along and assist, and I am not sure of a better way to write a conditionalized query. Commented Mar 4, 2018 at 23:03

2 Answers 2

1

Change:

data.Parameters.AddWithValue("\"" + placeholders[f] + "\"", parameters[f]);

to:

data.Parameters.AddWithValue(placeholders[f], parameters[f]);

placeholders[f] contains @/*FieldVar*/, which is the parameter name that AddWithValue is expecting. If you surround it with extra double quotes, you end up trying to use a parameter named "@/*FieldVar*/", which doesn't match your SQL query and causes the "field1 must be defined" error.

Sign up to request clarification or add additional context in comments.

Comments

0

If you have a column of DATE or DATETIME in the MySQL table, you must pass a parameter value of System.DateTime type, not a string with a formatted date.

List<object> parameters = new List<object>();
...
parameters.Add(fieldVar, DateTimePickerOnForm.Value);
...

5 Comments

I should have clarified, the first field is a varchar and I am passing a string, I grabbed a date one because it was the simplest snippet of form condition I could grab. I have had no time passing values into the form prior. Additionally, the issues is it saying the variable is undefined, not invalid.
Did you inspect the resulting query string exportQuery? Does it contain what you expect?
yes, it does build the query properly thankfully. I factored in spaces for it to read and then trim the final and add a semicolon based on how I do it. so adding the date just generated: SELECT * FROM /*Schema*/./*Table*/ WHERE *PK*/=@/*PKVar*/ AND *Field1*/=@*Field1Var*/ AND *Field2*/=@/*Field2Var*/;
Is some of your field names a reserved word in MySQL? You should enclose the field names in back tick characters (`) to avoid this problem. (Btw. does the sanitized query also look as expected?)
yes, every field is surrounded by (`) and no, no reserved words, Sorry for the secrecy, necessary evil. I have a troubleshooting output that I have going right now that spits out the entirety of the export query used, then each placeholder and variable as they should be going through the "data.Parameters.AddWithValue" section. everything appears correct.

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.