How to do select query in C# WCF service in Visual Studio and how to get the returned results?

103 Views Asked by At

I'm currently trying to view the details of the table using a given id. I need to use select query to retrieve the data from the database.

I tried working with ExecuteNonQuery, but it crashes. After I searched, I found people saying not to use ExecuteNonQuery for select statement and to use ExecuteReader instead, but it doesn't work as well and exception pops up.

This is the code:

con.Open(); 

SqlCommand cmd = new SqlCommand("select address from user where id=@x", con); 
SqlParameter p1 = new SqlParameter("@x", id);   
cmd.Parameters.Add(p1); 

SqlDataReader s = cmd.ExecuteReader(); 

if (s.HasRows) 
{
    while (s.Read()) 
    {
        add = s.ToString(); 
    } 
} 
else 
    add = "none"; 

con.Close(); 
return add; 

This is the exception on ExecuteReader line:

System.Data.SqlClient.SqlException HResult=0x80131904
Message=Incorrect syntax near the keyword 'user'.
Source=.Net SqlClient Data Provider StackTrace:

0

There are 0 best solutions below