I want to change a password for a user in MySQL which requires @
symbol. However, C# SQL command uses that as a parameter holder and because of that the following command fails.
command.CommandText = $"ALTER USER '{user}'@'%' IDENTIFIED BY '{password}'";
How does one escape or force DbCommand
to use literal @
?
I am aware of SQL injection issues. I am going this in a console app as one time maintenance to do some data migration.
2
Answers
It turns out that adding single quotes around the username solves the problem. For example:
command.CommandText = $"ALTER USER '{usr}'@'%' IDENTIFIED BY '{pwd}'"
works resulting in SQL command text ofALTER USER 'user1'@'%' IDENTIFIED BY 'pwd123'
. However, username does not have to be quoted if it does not have special characters. For example, the following SQL works fine when executed through MySQL client from command line:ALTER USER user1@'%' IDENTIFIED BY 'pwd123'
but the same SQL fails when executed throughMySqlCommand
resulting in error:Parameter '@'%'' must be defined
.The MySQL connector tries to parse SQL to implement named parameters, and seemingly offers no way to escape
@
; accounts and roles are the one syntax affected by it. Luckily, you’re using@'%'
, and@'%'
is the default.You might even be able to use parameters. If this works, you should – one-off or not, it’s just much cleaner.