Sunday, November 16, 2014

ADO.Net - SqlDataReader

Below is a sample usage of the SqlDataReader class in ADO.Net.
reader.HasRows checks if any rows are returned.


string connectionString = "Data Source=DataBaseServerName;Initial Catalog=DataBaseName;Persist Security Info=True;User ID=UserName;Password=Password;";
string query = "select eid, name, email from dbo.Employee where status=1";

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    SqlCommand command = new SqlCommand(query, connection);
                    connection.Open();

                    SqlDataReader reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine("Column1 : {0} | Column2 : {1} | Column3 : {2}", reader[0],                                          reader[1], reader[2]);
                        }
                    }
                    reader.Close();
                }
            }


No comments:

Post a Comment