2

I'm trying to connect SQL Server 2008 to c# windows application.
It's giving me an error.

try
{
    con = new SqlConnection("server=sameer-PC;database=Demo;Integrated Security=true;UID=admin;password=admin");
    //String query = "select * from user";

    con.Open();
    cmd = new SqlCommand("select * from user", con);

    Console.WriteLine("connection open{0}");

    SqlDataReader myReader = null;

    myReader = cmd.ExecuteReader();
    while (myReader.Read())
    {
         Console.Write((myReader["name"]));
    }
    con.Close();
}

Error:

A first chance exception of type

'System.Data.SqlClient.SqlException' occurred in System.Data.dll
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword 'user'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReadeThe thread 'vshost.RunParkingWindow' (0x820) has exited with code 0 (0x0).
The thread '<No Name>' (0xc80) has exited with code 0 (0x0).
Maximilian Ast
  • 3,369
  • 12
  • 36
  • 47

2 Answers2

8

user is a reserved keyword in SQL. So you need to wrap around with square brackets or Delimited Identifiers like this select * from [user]

Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
  • 1
    If this answer helped you please consider [accepting it](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). Accepting answers rewards those who helped you and it helps others, with the same problem, to find the correct answer. – David Rushton Jun 14 '16 at 09:02
0

You can try this:

try
{
   con = new SqlConnection("server=sameer-PC;database=Demo;Integrated Security=true;UID=admin;password=admin");
  con.Open();
  cmd = new SqlCommand("select * from [user]", con);

   Console.WriteLine("connection open{0}");

   SqlDataReader myReader = null;

   myReader = cmd.ExecuteReader();
   while (myReader.Read())
   {
     Console.Write((myReader["name"]));
   }
   con.Close();

}