article

Basic SqlDataReader Explained

Email
Submitted on: 1/1/2015 9:47:00 AM
By: Tyler Love (from psc cd)  
Level: Beginner
User Rating: By 9 Users
Compatibility: C#, ASP.NET
Views: 1204
 
     This is a short tutorial explaining how you would go about reading data from your database on to an application or an ASP.NET web page.

 
				1. Create a sqlConnection to your database using the sqlConnection tool in your tool box. Name it sqlMyCon


2. Create a sql command using the sqlCommand tool in your toolbox that will query and return a row that you are wanting. Name it sqlMyCmd. In this case I am wanting to return a specific row so I would do something like this:

SELECT * FROM MyTable
WHERE (ColumnName = '1234567')
That would return all the columns in the the table "MyTable". Where there was a row in the Column "ColumnName" that has the integer "1234567" in it.

3. Now you have done with that you get to write a few lines of code. So here is the example of how I would go about reading the data that is returned and inserting it into a web page or application. (Pretend I have a label named "lblData")


sqlMyCon.Open();
// This creates a datareader
SqlDataReader reader = sqlMyCmd.ExecuteReader();
reader.Read();
//This will select what column's data it will
// return using "GetString" remember it is zerobased
lblData.Text = reader.GetString(2);
sqlMyCon.Close();


4. Run it and make sure it works. If you would like to see something that uses that and does work go to http://www.junebughunter.net I made that site and all the content comes from a database using almost that exact same thing.


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.