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.
AddWithValuemeans the DB Engine has to guess at the real datatype. Given the nature of this thing, that means you will likely pass them asObjector string making it harder to guess correctly. I'd go back to the drawing board and avoid a general purpose method