Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server select query execution from c#

string user = "1234";
string strSQL = string.Format("Select * From User where UserId = '{0}'",user);
SqlCommand myCommand = new SqlCommand(strSQL, cnn);
reader = myCommand.ExecuteReader();

My User table consists of UserId and Password columns. The UserId column type is nchar and so I've used the single quotes. I get an error saying that

incorrect syntax near the keyword User"

(I guess the table name User is being referred to here).

I have the connection string and other database environment related things correctly for I've checked the database connection status and it is open(during program execution).

What is the error in the syntax? I'm unable to retrieve the rows from my table.

like image 368
Nithish Inpursuit Ofhappiness Avatar asked Jan 02 '13 10:01

Nithish Inpursuit Ofhappiness


1 Answers

User is a Keyword. Use square bracket around it to avoid the error. Select * from [User]

string strSQL = string.Format("Select * From [User] where UserId = '{0}'",user);

Also, you should always use parameterized query like below to prevent SQL Injection attack:

string strSQL = string.Format("Select * From [User] where UserId = @UserId");
like image 54
codingbiz Avatar answered Oct 16 '22 23:10

codingbiz