Sunday 16 September 2012

ADO.NET : Connected & Disconnected Environment!






ADO.NET provides a relatively common way to interact with data sources, but comes in different sets of libraries for each way you can talk to a data source. 

Core Objects of .NET Framework Data Providers

The following table outlines the four core objects that make up a .NET Framework data provider.
Object
Description
ConnectionEstablishes a connection to a specific data source. The base class for all Connectionobjects is the DbConnection class.
CommandExecutes a command against a data source. Exposes Parameters and can execute within the scope of a Transaction from a Connection. The base class for all Command objects is the DbCommand class.
DataReaderReads a forward-only, read-only stream of data from a data source. The base class for allDataReader objects is the DbDataReader class.
DataAdapterPopulates a DataSet and resolves updates with the data source. The base class for allDataAdapter objects is the DbDataAdapter class.

In addition to the core classes listed in the table above, a .NET Framework data provider also contains the classes listed in the following table.
Object
Description
TransactionEnables you to enlist commands in transactions at the data source. The base class for allTransaction objects is the DbTransaction class.
ParameterDefines input, output, and return value parameters for commands and stored procedures. The base class for all Parameter objects is the DbParameter class.

SqlConnection Object
The first thing you will need to do when interacting with a data base is to create a connection.  The connection tells the rest of the ADO.NET code which data base it is talking to.

Creating a SqlConnection Object:

 SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["NewGoMahadConnectionString"].ConnectionString );  
Table below describes common parts of a connection string.
table 1.  ADO.NET Connection Strings contain certain key/value pairs for specifying how to make a data base connection.  They include the location, name of the database, and security credentials.

Connection String Parameter Name
Description
Data Source
Identifies the server.  Could be local machine, machine domain name, or IP Address.
Initial Catalog
Data base name.
Integrated Security
Set to SSPI to make connection with user’s Windows login
User ID
Name of user configured in SQL Server.
Password
Password matching SQL Server User ID.
Integrated Security is secure when you are on a single machine doing development.  However, you will often want to specify security based on a SQL Server User ID with permissions set specifically for the application you are using.  The following shows a connection string, using the User ID and Password parameters:
web.config Code:


<configuration>
    <appSettings/>
    <connectionStrings>
  <remove name="LocalSqlServer" />
  <add name="LocalSqlServer" connectionString="Data Source=.\SQLExpress;Integrated Security=True;User Instance=True;AttachDBFilename=|DataDirectory|aspnetdb.mdf" />
  <add name="NewGoMahadConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\gomahad.mdf;Initial Catalog=gomahad;Integrated Security=True;User Instance=false" />
  <add name="gomahadConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\gomahad.mdf;Initial Catalog=gomahad;Integrated Security=True;User Instance=false" />
  <add name="gomahadConnectionStringSearch" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\gomahad.mdf;Initial Catalog=gomahad;Integrated Security=True;User Instance=false"
   providerName="System.Data.SqlClient" />
  <add name="gomahadConnectionStringCourseSearch" connectionString="Data Source=MAHAD-PC;Initial Catalog=gomahad;Integrated Security=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

SqlConnection conn = new SqlConnection(“Data Source=Karachi;Initial Catalog=gomahad;User ID=YourUserID;Password=YourPassword”);
Notice how the Data Source is set to DatabaseServer to indicate that you can identify a data base located on a different machine, over a LAN, or over the Internet.  Additionally, User ID and Password replace the Integrated Security parameter.
The sequence of operations occurring in the lifetime of a SqlConnection are as follows:
  1. Instantiate the SqlConnection.
  2. Open the connection.
  3. Pass the connection to other ADO.NET objects.
  4. Perform data base operations with the other ADO.NET objects.
  5. Close the connection.
SqlCommand Object
A SqlCommand object allows you to specify what type of interaction you want to perform with a data base.  For example, you can do select, insert, modify, and delete commands on rows of data in a data base table.

SqlDataReader Object

A SqlDataReader is a type that is good for reading data in the most efficient manner possible.  You can *not* use it for writing data.  SqlDataReaders are often described as fast-forward firehose-like streams of data.
You can read from SqlDataReader objects in a forward-only sequential manner.  Once you’ve read some data, you must save it because you will not be able to go back and read it again.

Example on the use of these ADO.NET objects…
Getting Data from database :
string sConnectionString = ConfigurationManager.ConnectionStrings["NewGoMahadConnectionString"].ConnectionString;
            SqlConnection oConn = new SqlConnection(sConnectionString);
            string sQueryString = “select * from tblUser”;
            SqlCommand oCommand = new SqlCommand(sQueryString);
            oCommand.Connection = oConn;
            oConn.Open();
            SqlDataReader oReader = oCommand.ExecuteReader();
            ArrayList oList = new ArrayList();
            if (oReader.HasRows)
            {
                while (oReader.Read())
                {
                    oList.Add(oReader[0].ToString());
                    oList.Add(oReader[1].ToString());                   
                }
            }
            oReader.Close();
            oConn.Close();
Getting single data from database:
 SqlCommand cmd = new SqlCommand(“select count(*) from Categories”, connection); 
 
int count = (int)cmd.ExecuteScalar();
Inserting data to database:
string conectionstring = ConfigurationManager.ConnectionStrings["NewGoMahadConnectionString"].ConnectionString ;
            SqlConnection connection = newSqlConnection(conectionstring);
            string querystring = “insert into customer values(‘”Guid.NewGuid() + “‘,’”+ txtCustName.Text+ “‘)”;
            SqlCommand oSqlCommand = new SqlCommand(querystring);
            connection.Open();
            oSqlCommand.Connection = connection;
            oSqlCommand.ExecuteNonQuery();

Working with Disconnected Data – The DataSet and SqlDataAdapter

A DataSet is an in-memory data store that can hold numerous tables.  DataSets only hold data and do not interact with a data source.  It is the SqlDataAdapter that manages connections with the data source and gives us disconnected behavior.  The SqlDataAdapter opens a connection only when required and closes it as soon as it has performed its task.  For example, the SqlDataAdapter performs the following tasks when filling a DataSet with data:
  1. Open connection
  2. Retrieve data into DataSet
  3. Close connection
and performs the following actions when updating data source with DataSet changes:
  1. Open connection
  2. Write changes from DataSet to data source
  3. Close connection
In between the Fill and Update operations, data source connections are closed and you are free to read and write data with the DataSet as you need.  These are the mechanics of working with disconnected data.

Creating a DataSet Object

There isn’t anything special about instantiating a DataSet.  You just create a new instance, just like any other object:
DataSet dsCustomers = new DataSet();
The DataSet constructor doesn’t require parameters.  However there is one overload that accepts a string for the name of the DataSet

Creating A SqlDataAdapter

The SqlDataAdapter holds the SQL commands and connection object for reading and writing data.  You initialize it with a SQL select statement and connection object:
SqlDataAdapter daCustomers = new SqlDataAdapter(
    “select CustomerID, CompanyName from Customers”, conn);
As indicated earlier, the SqlDataAdapter contains all of the commands necessary to interact with the data source. 
The Example of DataSet of select query is given below-
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        DataSet dataset = new DataSet();
        static void Main(string[] args)
        {

            Program p = new Program();
            p.TestRead();
            p.printTest();
            Console.ReadKey();
        }

        private void TestRead()
        {
            SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["NewGoMahadConnectionString"].ConnectionString);

            try
            {
                oConnection.Open();              
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = new SqlCommand(“select * from tblUser”, oConnection);
                adapter.Fill(dataset,“TEST”);
                oConnection.Close();
               
            }
            catch (SqlException oSqlExp)
            {
                Console.WriteLine(“” + oSqlExp.Message);
            }
            catch (Exception oEx)
            {
                Console.WriteLine(“” + oEx.Message);
            }
            finally
            {
                if (oConnection != null)
                {
                    oConnection.Close();
                }
            }
        }

29 comments:

Unknown said...

I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.

Java Training Institute Bangalore

tansitanu said...

My rather long internet look up has at the end of the day been compensated with pleasant insight to talk about with my family and friends.
amazon-web-services-training-in-bangalore

Unknown said...

I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.

Best Java Training Institute Chennai


Amazon Web Services Training in Chennai



Unknown said...

I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.

Best DevOps Training in Chennai

ganga pragya said...
This comment has been removed by the author.
Unknown said...

Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

rpa training in Chennai | best rpa training in chennai

rpa training in pune

rpa online training | rpa training in bangalore

rmouniak said...

It's a nice post I was really impressed by reading this Dot NET Online Course Hyderabad

janani said...

Just stumbled across your blog and was instantly amazed with all the useful information that is on it. Great post, just what i was looking for and i am looking forward to reading your other posts soon!
java training in chennai

java training in marathahalli | java training in btm layout

gowsalya said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
Best Devops Training in pune
advanced excel training in bangalore

SRI said...


This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 

best rpa training in chennai |
rpa training in chennai | rpa online training |
rpa training in chennai |
rpa training in bangalore
rpa training in pune
rpa training in marathahalli
rpa training in btm

john brito said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me
best rpa training in chennai
rpa training in chennai |
rpa online training
rpa course in bangalore
rpa training in pune
rpa training in marathahalli
rpa training in btm

Unknown said...

Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information.


rpa training in chennai |
best rpa training in chennai
rpa online training
rpa course in bangalore
rpa training in pune
rpa training in marathahalli
rpa training in btm

Mounika said...

I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!
python course in pune | python course in chennai | python course in Bangalore

sakthi said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.

best rpa training in chennai
rpa training in chennai |
rpa online training
rpa course in bangalore
rpa training in pune
rpa training in marathahalli
rpa training in btm

Unknown said...

Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
Java training in Bangalore |Java training in Rajaji nagar | Java training in Bangalore | Java training in Kalyan nagar

Java training in Bangalore | Java training in Kalyan nagar | Java training in Bangalore | Java training in Jaya nagar

Unknown said...

Appreciating the persistence you put into your blog and detailed information you provide

Data Science Training in Indira nagar
Data Science Training in btm layout
Python Training in Kalyan nagar
Data Science training in Indira nagar
Data Science Training in Marathahalli | Data Science training in Bangalore

dwarakesh said...

Howdy, would you mind letting me know which web host you’re utilizing? I’ve loaded your blog in 3 completely different web browsers, and I must say this blog loads a lot quicker than most. Can you suggest a good internet hosting provider at a reasonable price?


Best AWS Training Institute in BTM Layout Bangalore ,AWS Coursesin BTM


Best AWS Training in Marathahalli | AWS Training in Marathahalli

Amazon Web Services Training in Jaya Nagar | Best AWS Training in Jaya Nagar


AWS Training in BTM Layout |Best AWS Training in BTM Layout

AWS Training in Marathahalli | Best AWS Training in Marathahalli

dwarakesh said...

Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an email. I’ve got some recommendations for your blog you might be interested in hearing.


Amazon Web Services Training in Pune | Best AWS Training in Pune


AWS Training in Chennai | Best Amazon Web Services Training in Chennai


Amazon Web Services Training in Chennai |Best AWS Training in Chennai


Amazon Web Services Online Training | Online Amazon Web Services Certification Course Training

Sherin Alfonsa said...

Mind blowing content!! Thanks for uploading
Selenium Training in Chennai
selenium Classes in chennai
iOS Training in Chennai
Digital Marketing Training in Chennai
Android Training
Android Training in Chennai
Big Data Training in Chennai

DeepikaOrange said...

Really I Appreciate The Effort You Made To Share The Knowledge. This Is Really A Great Stuff For Sharing. Keep It Up . Thanks For Sharing.

Angular Training in Chennai
Angular JS Training in Chennai

Raji said...

More informative,thanks for sharing with us.
this blog makes the readers more enjoyable.keep add more info on your page.
Devops Training in Chennai | Devops Training Institute in Chennai

sasitamil said...

A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
devops online training

aws online training

data science with python online training

data science online training

rpa online training

kavithasathish said...

Excellent blog with good information it is really useful.
Japanese Classes in Chennai
Japanese Language Course in Chennai
Spoken English Classes in Chennai
French Classes in Chennai
pearson vue
German Classes in Chennai
Japanese Classes in Adyar
Japanese Classes in VelaChery
IELTS Coaching in anna nagar
ielts coaching in chennai anna nagar

Janu said...

Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work



Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery



saran said...

"Good Posting. Extra-ordinary way to narrate the concepts. Thanks for sharing..
Digital Marketing Training Course in Chennai | Digital Marketing Training Course in Anna Nagar | Digital Marketing Training Course in OMR | Digital Marketing Training Course in Porur | Digital Marketing Training Course in Tambaram | Digital Marketing Training Course in Velachery

"

aarthi said...


This is such a good post. One of the best posts that I\'ve read in my whole life. I am so happy that you chose this day to give me this.
Please, continue to give me such valuable posts. Cheers!
Java training in Chennai

Java training in Bangalore

Java training in Hyderabad

Java Training in Coimbatore

Java Online Training

Anonymous said...

no deposit bonus forex 2021 - takipçi satın al - takipçi satın al - takipçi satın al - takipcialdim.com/tiktok-takipci-satin-al/ - instagram beğeni satın al - instagram beğeni satın al - google haritalara yer ekleme - btcturk - tiktok izlenme satın al - sms onay - youtube izlenme satın al - google haritalara yer ekleme - no deposit bonus forex 2021 - tiktok jeton hilesi - tiktok beğeni satın al - binance - takipçi satın al - uc satın al - finanspedia.com - sms onay - sms onay - tiktok takipçi satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - tiktok takipçi satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - perde modelleri - instagram takipçi satın al - instagram takipçi satın al - cami avizesi - marsbahis

Anonymous said...

mmorpg
İnstagram takipci satin al
Tiktok Jeton Hilesi
TİKTOK JETON HİLESİ
SAC EKİMİ ANTALYA
TAKİPÇİ SATIN AL
instagram takipçi satın al
Metin2 Pvp Serverler
TAKİPCİ SATİN AL

Anonymous said...

yeni perde modelleri
sms onay
mobil ödeme bozdurma
nft nasıl alınır
ankara evden eve nakliyat
trafik sigortası
DEDEKTÖR
web sitesi kurma
Ask kitaplari

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More