skip to Main Content

I am running the below MySQL query from c# code and the backlash is recognized only I enter it twice. Is it something I am missing in MYSQL database settings that’s causing this

Not Working

SELECT * FROM user where username='Basd';

Working

SELECT * FROM user where username='B\asd';

But in the username column it is saved as ‘Basd’.

Do I need to charset or anything to make it work with single backsplash?

2

Answers


  1. The backslash character () is used to escape characters or to create special ones like tabs (t) and line breaks (r and n). This results in having to escape the character itself for it to be recognized as a part of the string in this case the SQL query.

    In your example when using just a single backslash "a" gets translated into an ASCII character with the hex value of 07

    Login or Signup to reply.
  2. Use MySqlParameter, which will avoid SQL injection and also escape the string for you correctly:

    using var command = new MySqlCommand("SELECT * FROM user where username=@username;", yourConnection);
    command.Parameters.AddWithValue("@username", @"Basd");
    using var reader = command.ExecuteReader();
    // read data
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search