Saturday, 9 November 2013

SqlClient Read Data in database using SqlDataReader - C#

Leave a Comment
This tutorial show how to read database using SqlDataReader in database using SqlClient driver to connect to database.

Read here to read data in database and pass to DataTable

Requirement in this tutorial are :

  1. using System.Data.SqlClient;
  2. using System.Data;

The Example Read Data using SqlDataReader :

            DataSet dataSetTable = new DataSet();
            SqlConnection dbConn = new SqlConnection("<connection string>");
            SqlCommand dbComm = new SqlCommand("<sql statement or procedure name>", dbConn);
            SqlDataReader dbReader;
            //set command type is procedure if you are using store procedure
            //else remove this line
            dbComm.CommandType = CommandType.StoredProcedure;

            try
            {                
                dbConn.Open();
                dbReader = dbComm.ExecuteReader();
                if (dbReader.HasRows) //check if reader have any row
                {
                    while (dbReader.Read())
                    {
                        //the process to read will be place here.
                        //every looping will read for each row return to dbReader
                        //example 
                        var valueRowForColumn = dbReader["<column Name>"];
                    }
                }
                else
                {
                    //do something if no row return
                }
                dbReader.Close();
            }
            catch (SqlException sqlEx)
            {
                MessageBox.Show(sqlEx.Message);                
            }
            finally
            {
                dbConn.Close();                
            }            
            





By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.