Logo

Navigation
  • Home
  • Services
    • ERP Solutions
    • Implementation Solutions
    • Support and Maintenance Solutions
    • Custom Solutions
    • Upgrade Solutions
    • Training and Mentoring
    • Web Solutions
    • Production Support
    • Architecture Designing
    • Independent Validation and Testing Services
    • Infrastructure Management
  • Expertise
    • Microsoft Development Expertise
    • Mobile Development
    • SQL Server Database and BI
    • SAP BI, SAP Hana, SAP BO
    • Oracle and BI
    • Oracle RAC
  • Technical Training
    • Learn Data Management
      • Business Intelligence
      • Data Mining
      • Data Modeling
      • Data Warehousing
      • Disaster Recovery
    • Learn Concepts
      • Application Development
      • Client Server
      • Cloud Computing Tutorials
      • Cluster Computing
      • CRM Tutorial
      • EDI Tutorials
      • ERP Tutorials
      • NLP
      • OOPS
      • Concepts
      • SOA Tutorial
      • Supply Chain
      • Technology Trends
      • UML
      • Virtualization
      • Web 2.0
    • Learn Java
      • JavaScript Tutorial
      • JSP Tutorials
      • J2EE
    • Learn Microsoft
      • MSAS
      • ASP.NET
      • ASP.NET 2.0
      • C Sharp
      • MS Project Training
      • Silverlight
      • SQL Server 2005
      • VB.NET 2005
    • Learn Networking
      • Networking
      • Wireless
    • Learn Oracle
      • Oracle 10g
      • PL/SQL
      • Oracle 11g Tutorials
      • Oracle 9i
      • Oracle Apps
    • Learn Programming
      • Ajax Tutorial
      • C Language
      • C++ Tutorials
      • CSS Tutorial
      • CSS3 Tutorial
      • JavaScript Tutorial
      • jQuery Tutorial
      • MainFrame
      • PHP Tutorial
      • VBScript Tutorial
      • XML Tutorial
    • Learn Software Testing
      • Software Testing Types
      • SQA
      • Testing
  • Career Training
    • Career Improvement
      • Career Articles
      • Certification Articles
      • Conflict Management
      • Core Skills
      • Decision Making
      • Entrepreneurship
      • Goal Setting
      • Life Skills
      • Performance Development
      • Personal Excellence
      • Personality Development
      • Problem Solving
      • Relationship Management
      • Self Confidence
      • Self Supervision
      • Social Networking
      • Strategic Planning
      • Time Management
    • Education Help
      • Career Tracks
      • Essay Writing
      • Internship Tips
      • Online Education
      • Scholarships
      • Student Loans
    • Managerial Skills
      • Business Communication
      • Business Networking
      • Facilitator Skills
      • Managing Change
      • Marketing Management
      • Meeting Management
      • Process Management
      • Project Management
      • Project Management Life Cycle
      • Project Management Process
      • Project Risk Management
      • Relationship Management
      • Task Management
      • Team Building
      • Virtual Team Management
    • Essential Life Skills
      • Anger Management
      • Anxiety Management
      • Attitude Development
      • Coaching and Mentoring
      • Emotional Intelligence
      • Stress Management
      • Positive Thinking
    • Communication Skills
      • Conversation Skills
      • Cross Culture Competence
      • English Vocabulary
      • Listening Skills
      • Public Speaking Skills
      • Questioning Skills
    • Soft Skills
      • Assertive Skills
      • Influence Skills
      • Leadership Skills
      • Memory Skills
      • People Skills
      • Presentation Skills
    • Finding a Job
      • Etiquette Tips
      • Group Discussions
      • HR Interviews
      • Interview Notes
      • Job Search Tips
      • Resume Tips
      • Sample Resumes
 

Accessing Data with C#

By Exforsys | on March 19, 2005 |
ASP.NET

This tutorial explains about Accessing Data with C# with an Overview of ADO.NET, Connecting to Data , Executing Commands , Working with Data and Choosing an ADO.NET Provider along with the Project files used in this.

 

ASP.NET: Accessing Data with C#

 Introduction:

When working with classic asp we had ADO, object model for communication with the database. Microsoft.NET has introduced ADO.NET components that lets the developer communicate with the database more efficiently and easily. In this article we will see how we can make use of the ADO.NET classes to perform different operations on the database.

ADO. NET Classes:

ADO .NET classes are put in the System.data namespace. You can access the classes using the following code:

using System.Data.SqlClient;

using System.Data.Odbc;

using System.Data.OleDb;

using System.Data.Oracle;

Different classes are used for different purpose.

System.Data.SqlClient: This class is used to communicate with the Sql Server database. The database can be version 7.0 or version 2000.

System.Data.SqlClient: This class is used to perform operations on the MySQL databases.

System.Data.OleDb: This class is used to perform operations on the Access Database.

System.Data.Oracle: This class is used to perform operations on the Oracle database.

In this article we will focus on the Sql Server 2000 database and hence we will be using System.Data.SqlClient namespace to perform different operations on the Sql Server 2000 Database.

Making the database connection:

Let’s see how we can make a database connection. There are several ways of making a database connection. You can simple drag and drop the database connection on the asp.net web form and the connection will be made. Let’s see how we can do that:

Open you Visual Studio.NET and start a new asp.net web application. In the toolbox you will see a tab called data. Click on the tab and it will dropdown showing various ADO objects. Drag and Drop the SqlConnection object on the screen. As soon as you drop the connection object you will see it at the bottom of the screen.

Right click on the connection object and select properties. In the properties you can see the property named "ConnectionString". When you click on it will take you to a wizard where you can select your database. In this article I will be using Northwind database which can be found in every Sql Server 2000 database.

Once you select the database, test your connection by clicking on the Test connection button. If the connection is correct a message box will pop saying that the connection has been tested and connection is right.

Problems using this approach of making the connection String:

As you have just seen that we just dragged and dropped the connection string on the screen and the new connection to the database was made in seconds. This approach should never be used since if in the future you change your connection string you will have to change every where in the application.

Using Web.config to store the connection String:

As you can see above that you can make your connection string with just one line. Take a look at the "key" represents the keyword that we will use to refer to it in our application.

"value" contains the connection string.

"database" contains the name of the database which in this case is Northwind.

I have to point out that saving the connection string like this is not secure. Usually you store the connection string after encrypting it. I will not perform encryption in this article and keep the article simple enough.

Accessing database from webpage:

Now you have added the connection string in the web.config file. Let’s see some code that we can use to access the database. We want to load some data from the database when the page is loaded for the first time.

private void Page_Load(object sender, System.EventArgs e)

{

if(!Page.IsPostBack)

{

string connectionString = (string) ConfigurationSettings.AppSettings["ConnectionString"];

SqlConnection myConnection = new SqlConnection(connectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories",myConnection);

DataSet ds = new DataSet();

ad.Fill(ds,"Categories");


myDataGrid.DataSource = ds;

myDataGrid.DataBind();


}

}

First, we check that if it’s not a postback we load data. For this example to work you need to add the namespace:

using System.Configuration;

Let’s see what is going on here:

1) string connectionString receives the string from the web.config file which is referred by the "ConnectionString" key we set in the web.config file.

2) We make the object of the SqlConnection class which deals with SQL Server databases.

3) We made the data adapter object. Data adapter is a kind of connection to the database. In the data adapter object we specify that what we want from the database. In this case we want all the rows of the Categories table.

NOTE:

Always use stored procedures for accessing the data. Accessing or running Ad-hoc queries are dangerous as they are open for SQL Injections.

4) Next we made an instance of the DataSet class. DataSet will contain the result of the SqlDataAdapter even if the database connection is not made.

5) Later, we filled the dataset with the data using dataadapter.

6) And finally we assigns the datagrid to the dataset and binds it on the screen.

Pretty simple right?

Lets see if we can improve the code above:

private void Page_Load(object sender, System.EventArgs e)

{

if(!Page.IsPostBack)

{

string connectionString = (string) ConfigurationSettings.AppSettings["ConnectionString"];

SqlConnection myConnection = new SqlConnection(connectionString);

SqlDataReader reader = null;

SqlCommand myCommand = new SqlCommand("GetData",myConnection);

myCommand.CommandType = CommandType.StoredProcedure;

try

{

myConnection.Open();

reader = myCommand.ExecuteReader();

myDataGrid.DataSource = reader;

myDataGrid.DataBind();

}

catch(Exception ex)

{

// Catches and logs the exception

}

finally

{

reader.Close();

myConnection.Close();

}


}

}

In the code above we are using the SqlCommand object and stored procedure. You might have noted SqlDataReader, if you want to merely iterate through the database rows and select them its best to use SqlDataReader since its much faster than DataSet.

Finally we catch exceptions if any of them are generated and closes the connection.

I hope you liked the article happy coding !

Download Project Files

« « SQL Unit Testing Tools
MSAS : The Wizards » »

Author Description

Avatar

Editorial Team at Exforsys is a team of IT Consulting and Training team led by Chandra Vennapoosa.

Free Training

RSSSubscribe 392 Followers
  • Popular
  • Recent
  • Managing Data with ADO.NET DataSets and C#

    April 8, 2005 - 0 Comment
  • Creating and consuming XML Web Services with C#

    April 14, 2005 - 0 Comment
  • ASP .NET Migration and Interoperability

    April 24, 2005 - 0 Comment
  • Managing State with ASP.NET and C#

    May 3, 2005 - 0 Comment
  • ASP.NET with C# Training Launch

    February 19, 2005 - 0 Comment
  • Caching in ASP.NET

    May 9, 2005 - 0 Comment
  • Introduction to ASP.NET with C#

    February 20, 2005 - 0 Comment
  • Configuring and Deploying ASP.NET Applications

    May 14, 2005 - 0 Comment
  • ASP.NET with C# Training Course Outline

    February 19, 2005 - 0 Comment
  • Securing ASP.NET Applications with C#

    May 14, 2005 - 0 Comment
  • Securing ASP.NET Applications with C#

    May 14, 2005 - 0 Comment
  • Configuring and Deploying ASP.NET Applications

    May 14, 2005 - 0 Comment
  • Caching in ASP.NET

    May 9, 2005 - 0 Comment
  • Managing State with ASP.NET and C#

    May 3, 2005 - 0 Comment
  • ASP .NET Migration and Interoperability

    April 24, 2005 - 0 Comment
  • Creating and consuming XML Web Services with C#

    April 14, 2005 - 0 Comment
  • Managing Data with ADO.NET DataSets and C#

    April 8, 2005 - 0 Comment
  • ASP.NET Using the DataList and Repeater, Datagrid Controls

    March 26, 2005 - 0 Comment
  • Using Rich Server Controls with C#

    March 12, 2005 - 0 Comment
  • ASP .NET: Validating User Input with C#

    March 4, 2005 - 0 Comment

Exforsys e-Newsletter

ebook
 

Related Articles

  • Securing ASP.NET Applications with C#
  • Configuring and Deploying ASP.NET Applications
  • Caching in ASP.NET
  • Managing State with ASP.NET and C#
  • ASP .NET Migration and Interoperability

Latest Articles

  • Project Management Techniques
  • Product Development Best Practices
  • Importance of Quality Data Management
  • How to Maximize Quality Assurance
  • Utilizing Effective Quality Assurance Strategies
  • Sitemap
  • Privacy Policy
  • DMCA
  • Trademark Information
  • Contact Us
© 2023. All Rights Reserved.IT Training and Consulting
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT