Ken

Ken

  • 0
  • 110
  • 0

Help with parameters passing a column to a MySql query

Jul 13 2017 2:53 AM
Hi.  I have a function that returns a dictionary with info pulled from a database.  The first parameter of the function is a string of the column to search, the second a string with the value.  I am doing this: 
  1. Dictionary<string, string> getData(string indexfield, string indexvalue) {  
  2.   using (MySqlConnection DB = getConnection()) {  
  3.     using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM customers WHERE ?if = ?iv", DB) {  
  4.       DB.Open();  
  5.       cmd.Parameters.AddWithValue("?if", indexfield);  
  6.       cmd.Parameters.AddWithValue("?iv", indexvalue);  
  7.       using (MySqlDataReader RS = cmd.ExecuteReader()) {  
  8.         DataTable schemaTable = RS.GetSchemaTable();  
  9.         if (!RS.HasRows) { MessageBox.Show("debug"); return ret; }
  10.         while (RS.Read()) {  
  11.           foreach (DataRow fld in schemaTable.Rows) {  
  12.             ret.Add(fld["ColumnName"].ToString(), RS[fld["ColumnName"].ToString()].ToString());  
  13.           }  
  14.         }  
  15.       }  
  16.       DB.Close();  
  17.     }  
  18.   }  
 When I run that, I get the "debug" messagebox indicating no rows.  I enabled the general log in MySQL, and I see this when passing field cid and value 5:
 
SELECT * FROM customers WHERE 'cid' = '5'
 
I copied that and ran the query, it failed.  Once I made it cid instead of 'cid', it worked fine.  Why is C# adding quotes around my field?  Is it because the variable being passed to cmd.Parameters.AddWithValue is a string?  Is there any way to stop that? 

Answers (1)