Reputation: 95
I am trying to read a string that includes a backslash in it from a sql table. For some reason I can not pass the back slash within the string. My string is the user name and its in this format: Domain\username I send it to the table as so:
SqlCommand scomm = new SqlCommand();
SqlDataReader sr;
string nameOfUser = "Domain\userName";
scomm.CommandText = "SELECT * FROM tableOfUsers WHERE UserName=" + nameOfUser;
sr = scomm.ExecuteReader();
During the debug I can see that another backslash is added as an escape character however I don't know what happens with the sql part and why an exception is thrown. I tried using @ but that didn't help either. I would appreciate any help you can provide me.
Upvotes: 3
Views: 6447
Reputation: 94645
Use SqlParameter
.
string nameOfUser = @"Domain\userName";
scomm.CommandText = "SELECT * FROM tableOfUsers WHERE UserName=@username";
scomm.Parameters.Add("@username",SqlDbType.VarChar,30).Value=nameOfUser;
//open the connection
SqlDataReader sr=scomm.ExecuteReader();
if(sr.Read()) // use while loop when one or more exists
{
Console.WriteLine(sr["columnName"] + " or use column ordinal : " + sr[0]);
}
Upvotes: 10
Reputation: 15861
Use SqlParameter.Sql Parameter Documentation. as the SqlPrameter Class will provide the functionality to avoid Sql Injections and other issues, which db not allowed.
string UserName = @"Domain\userName";
scomm.CommandText = "SELECT * FROM tableOfUsers WHERE UserName=@username";
scomm.Parameters.AddWithValue("@username",UserName);
Upvotes: 2
Reputation: 83356
You can use a string literal
string nameOfUser = @"Domain\userName";
or escape your backslash
string nameOfUser = "Domain\\userName";
Your query also has some errors in it. You theoretically need to put quotes around nameOfUser
string nameOfUser = @"Domain\userName";
scomm.CommandText = "SELECT * FROM tableOfUsers WHERE UserName= '" + nameOfUser + "'";
But you should really use a parameterized query
string nameOfUser = @"Domain\userName";
scomm.CommandText = "SELECT * FROM tableOfUsers WHERE UserName= @name";
scomm.Parameters.AddWithValue("@name", nameOfUser);
This will protect your against Sql Injection attacks, and, more mundanely, will allow your query to work with people whose names have a '
—like "O'Reilly"
Upvotes: 5