-3

I want to know how to select data from MariaDB in C# with variable value in where condition. Please see my code, I am getting this error:

MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '@gmail.com' at line 1'

Please correct me with my code if I am wrong.

Here is my code

var2 = Forms.frmLogin.var1;
connection2.Open();
string selectQuery = "Select Role from car_dealer.users where email = "+var2+" ";
command = new MySqlCommand(selectQuery, connection2);
mdr = command.ExecuteReader();
if (mdr.Read())
{
    var3 = mdr.GetString("Role");
}

//lblUsername.Text = var2;
connection2.Close();
MessageBox.Show(var3); 
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
sajid
  • 1
  • 2
  • 2
    Does this answer your question? [What are good ways to prevent SQL injection?](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection) • [SqlCommand Parameters Add vs. AddWithValue](https://stackoverflow.com/questions/21110001/sqlcommand-parameters-add-vs-addwithvalue) –  Aug 17 '21 at 13:13
  • 2
    You forgot quotes in case of email is a string/text/varchar column... `'" + var2 + "'` but don't do that and use SQL Parameters. –  Aug 17 '21 at 13:13
  • 1
    Use parameters to prevent SQLi and *syntax* issues. – Trevor Aug 17 '21 at 13:17

2 Answers2

-2

Could you change the query with this?

string selectQuery = "Select Role from car_dealer.users  where email = '"+var2+"' ";
-2

I think you need to wrap the email address within quotes.

You can use C# string interpolation syntax rather than concatenating strings.

string selectQuery = $"Select Role from car_dealer.users where email = '{var2}'";
Dhilip H
  • 594
  • 4
  • 10