SqlCommand.ExecuteNonQuery
You can use ExecuteNonQuery to perform directory operations (for example, querying a database structure or creating database objects such as tables), or to modify data in a database without using a DataSet by doing UPDATE, INSERT or DELETE. Although ExecuteNonQuery does not return rows, any output parameters or return values โโassociated with the parameters are populated with data. For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists in an inserted or updated table, the return value includes the number of rows affected by both the insert operation and the update, as well as the number of rows affected by the trigger or triggers. For all other types of operators, the return value is -1. If a rollback occurs, the return value is -1.
SqlCommand.ExecuteScalar Method Executes the Transact-SQL statement for the join and returns the number of rows affected.
So it will not work. statements returned by the SELECT statement, you must use the ExecuteScalar method.
Link: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx
So try below code:
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password="); conn.Open(); SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip ", conn); command.Parameters.AddWithValue("@zip","india"); // int result = command.ExecuteNonQuery(); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { Console.WriteLine(String.Format("{0}",reader["id"])); } } conn.Close();
source share