SlideShare a Scribd company logo
1 of 17
For Beginners – ADO.Net
Contents
•   Introduction to ADO.NET

•   The SqlConnection Object

•   The SqlCommand Object

•   Reading Data with the SqlDataReader

•   Working with Disconnected Data - The DataSet and SqlDataAdapter

•   Adding Parameters to Commands

•   Using Stored Procedures
Introduction to ADO.NET
• ADO.NET is an object-oriented set of libraries that allows you to interact with data sources.

• Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or
  an XML file.

• 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. These libraries are called Data
  Providers and are usually named for the protocol or data source type they allow you to interact
  with.

• ADO.NET Data Providers
ADO.NET-related Namespaces
.NET Data Providers Hierarchy
ADO.Net Architecture
ADO.NET Objects
•   Connection Object :                    The connection helps identify the database server, the database
    name, user name, password, and other parameters that are required for connecting to the data base. A
    connection object is used by command objects so they will know which database to execute the
    command on.

•   Command Object :                      Use a command object to send SQL statements to the database.
    A command object uses a connection object to figure out which database to communicate with.

•   DataReader Object :          The data reader object allows you to obtain the results of a SELECT
    statement from a command object. For performance reasons, the data returned from a data reader is a fast
    forward-only stream of data.

•   DataSet Object :                           DataSet objects are in-memory representations of data. They
    contain multiple Datatable objects, which contain columns and rows, just like normal database tables.
    You can even define relations between tables to create parent-child relationships. The DataSet is an
    object that is used by all of the Data Providers, which is why it does not have a Data Provider specific
    prefix.

•   DataAdapter Object :                      The data adapter fills a DataSet object when reading the data
    and writes in a single batch when persisting changes back to the database. A data adapter contains a
    reference to the connection object and opens and closes the connection automatically when reading from
    or writing to the database.

•   CommandBuilder :                          By default dataadapter contains only the select command and it
    doesn’tcontain insert, update and delete commands. To create insert, update and delete commands for the
    dataadapter, commandbuilder is used. It is used only to create these commands for the dataadapter and
    has no other purpose.
SqlConnection Object
•   The connection tells the rest of the ADO.NET code which database it is talking to. It manages all of the
    low level logic associated with the specific database protocols.

•   Declare and instantiate the SqlConnection as shown below:
          SqlConnection conn = new SqlConnection
                      ( "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

•   ADO.NET Connection String Parameters


     Parameter
                          Description
     Name
                          Identifies the server. Could be local machine, machine domain name, or IP
     Data Source
                              Address.
     Initial Catalog      Database name.
     Integrated
                          Set to SSPI to make connection with user's Windows login
     Security
     User ID              Name of user configured in SQL Server.
     Password             Password matching SQL Server User ID.
SqlCommand & SqlDataReader Object
•   SqlCommand object allows you to specify what type of interaction you want to perform with
    a database. For example, you can do select, insert, modify, and delete commands on rows of
    data in a database table.
•   Creating a SqlCommand Object
    SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);




•   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.
•   Creating a SqlDataReader Object
•   Getting an instance of a SqlDataReader is a little different than the way you instantiate other
    ADO.NET objects. You must call ExecuteReader on a command object, like this:
          SqlDataReader rdr = cmd.ExecuteReader();
SqlCommand Methods
•   1) ExecuteReader -Querying Data                   •   Similarly ExecuteNonQuery can be used to
•   Used to retrieve data records for viewing. It         update a record using below query string
    returns a SqlDataReader object.                       // prepare command string
•   Example:                                               string updateString = @"
    // 1. Instantiate a new command with a query              update Categories
                                                              set CategoryName = 'Other'
    and connection                                            where CategoryName = 'Miscellaneous'";
    SqlCommand cmd = new SqlCommand("select
    CategoryName from Categories", conn);
                                                      •   Similarly ExecuteNonQuery can be used to
    // 2. Call Execute reader to get query results        delete a record using below query string
    SqlDataReader rdr = cmd.ExecuteReader();              // prepare command string
                                                           string deleteString = @"
                                                              delete from Categories
•   2) ExecuteNonQuery (Insert/Update/Delete)                 where CategoryName = 'Other'";
•   To insert data into a database, use the
    ExecuteNonQuery method of the SqlCommand
    object.
                                                          3) ExecuteScalar - Getting Single values
    // prepare command string                         •
     string insertString = @"                             Used to get count, sum, average, or other
        insert into Categories                            aggregated value from a database.
        (CategoryName, Description)                       // 1. Instantiate a new command
        values ('Miscellaneous', 'Whatever doesn''t        SqlCommand cmd = new SqlCommand("select
    fit elsewhere')";                                     count(*) from Categories", conn);

     // 1. Instantiate a new command with a query          // 2. Call ExecuteNonQuery to send command
    and connection                                         int count = (int)cmd.ExecuteScalar();
     SqlCommand cmd                                   •   The query in the SqlCommand constructor
    = new SqlCommand(insertString, conn);                 obtains the count of all records from the
                                                          Categories table. This query will only return a
    // 2. Call ExecuteNonQuery to send command            single value.
    cmd.ExecuteNonQuery();
Connected Example:
• Example in attached file to retrieve, insert, update,
  delete record from data table. Double click on below
  link to open notepad file.




                  ConnectedExample.txt
Working with Disconnected Data
•   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:
•   Open connection
•   Retrieve data into DataSet
•   Close connection

•   and performs the following actions when updating data source with DataSet changes:
•   Open connection
•   Write changes from DataSet to data source
•   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.
Disconnected Example
•   Example below in text file use DataSet and SqlDataAdapter to get customer records & display in
    datagrid. Datagrid is editable &changes can be saved using “Update” button. Double click below file to
    open.




                             DisconnectedEmaple.txt
Adding Parameters to Commands
•     Using parameterized queries is a three step process:

1)    Construct the SqlCommand command string with parameters.
        SqlCommand cmd = new SqlCommand( "select * from Customers where city = @City", conn);

1)    Declare a SqlParameter object, assigning values as appropriate.
      SqlParameter param = new SqlParameter(); param.ParameterName = "@City"; param.Value =
      inputCity;

3)    Assign the SqlParameter object to the SqlCommand object's Parameters property.
      cmd.Parameters.Add(param);

4)    Below is complete console application example double click to open.




                             AddingParameterExample.txt
Using Stored Procedures
•   A stored procedures is a pre-defined, reusable routine that is stored in a database.
•   SQL Server compiles stored procedures, which makes them more efficient to use.
•   Therefore, rather than dynamically building queries in your code, you can take advantage of
    the reuse and performance benefits of stored procedures.

•   Executing a Stored Procedure
    // 1. create a command object identifying the stored procedure
    SqlCommand cmd = new SqlCommand( “<<StoredProcName>>", conn);
    // 2. set the command object so it knows to execute a stored procedure
    cmd.CommandType = CommandType.StoredProcedure;

•   Sending Parameters to Stored Procedures
    SqlCommand cmd = new SqlCommand( "CustOrderHist", conn);
    // 2. set the command object so it knows to execute a stored procedure
    cmd.CommandType = CommandType.StoredProcedure;
    // 3. add parameter to command, which will be passed to the stored procedure
    cmd.Parameters.Add( new SqlParameter("@CustomerID", custId));

•   The name of the parameter passed as the first parameter to the SqlParameter constructor
    must be spelled exactly the same as the stored procedure parameter.
Stored Procedure Example
•   Below example uses 2 procedures to get

•   top 10 expensive products

•   Customer specific orders

Double click to open example below




                                StoredProcedureExample.txt
Thank You

More Related Content

What's hot

Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Salman Memon
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code firstConfiz
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react formYao Nien Chung
 
Finalize() method
Finalize() methodFinalize() method
Finalize() methodJadavsejal
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationRandy Connolly
 
Intro to Big Data and NoSQL
Intro to Big Data and NoSQLIntro to Big Data and NoSQL
Intro to Big Data and NoSQLDon Demcsak
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net frameworkArun Prasad
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQLEhsan Hamzei
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Aijaz Ali Abro
 
Databind in asp.net
Databind in asp.netDatabind in asp.net
Databind in asp.netSireesh K
 

What's hot (20)

Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code first
 
Collections in-csharp
Collections in-csharpCollections in-csharp
Collections in-csharp
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Finalize() method
Finalize() methodFinalize() method
Finalize() method
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Intro to Big Data and NoSQL
Intro to Big Data and NoSQLIntro to Big Data and NoSQL
Intro to Big Data and NoSQL
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net framework
 
Java Docs
Java DocsJava Docs
Java Docs
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
PHP Presentation
PHP PresentationPHP Presentation
PHP Presentation
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
Databind in asp.net
Databind in asp.netDatabind in asp.net
Databind in asp.net
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 

Viewers also liked

Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NETrchakra
 
Latest Advance Animated Ado.Net With JDBC
Latest Advance Animated Ado.Net With JDBC Latest Advance Animated Ado.Net With JDBC
Latest Advance Animated Ado.Net With JDBC Tarun Jain
 
ADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaSonu Vishwakarma
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05Niit Care
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vbSalim M
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NETRajkumarsoy
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1Kumar S
 
Asp.net mvc filters
Asp.net mvc filtersAsp.net mvc filters
Asp.net mvc filtersEyal Vardi
 
Vb net xp_05
Vb net xp_05Vb net xp_05
Vb net xp_05Niit Care
 
HCL Corporate Presentation Nov 2008
HCL Corporate Presentation Nov 2008HCL Corporate Presentation Nov 2008
HCL Corporate Presentation Nov 2008Semalytix
 
Ado.net session01
Ado.net session01Ado.net session01
Ado.net session01Niit Care
 

Viewers also liked (20)

Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ado.net
Ado.netAdo.net
Ado.net
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Ado .net
Ado .netAdo .net
Ado .net
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Latest Advance Animated Ado.Net With JDBC
Latest Advance Animated Ado.Net With JDBC Latest Advance Animated Ado.Net With JDBC
Latest Advance Animated Ado.Net With JDBC
 
ADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaADO .NET by Sonu Vishwakarma
ADO .NET by Sonu Vishwakarma
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
Debugging
DebuggingDebugging
Debugging
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vb
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1
 
Asp.net mvc filters
Asp.net mvc filtersAsp.net mvc filters
Asp.net mvc filters
 
Vb net xp_05
Vb net xp_05Vb net xp_05
Vb net xp_05
 
HCL Corporate Presentation Nov 2008
HCL Corporate Presentation Nov 2008HCL Corporate Presentation Nov 2008
HCL Corporate Presentation Nov 2008
 
Asp.Net Tutorials
Asp.Net TutorialsAsp.Net Tutorials
Asp.Net Tutorials
 
Ado.net session01
Ado.net session01Ado.net session01
Ado.net session01
 

Similar to For Beginers - ADO.Net

Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxsridharu1981
 
The sql connection object
The sql connection objectThe sql connection object
The sql connection objectSharat Chandu
 
Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Alexey Furmanov
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desaijmsthakur
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12Sisir Ghosh
 
Ado.net by Awais Majeed
Ado.net by Awais MajeedAdo.net by Awais Majeed
Ado.net by Awais MajeedAwais Majeed
 
Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net ArchitectureUmar Farooq
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdfManalAg
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot netSynapseindiappsdevelopment
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2Neeraj Mathur
 
LECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptxLECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptxAOmaAli
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentalsMadhuri Kavade
 

Similar to For Beginers - ADO.Net (20)

Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptx
 
The sql connection object
The sql connection objectThe sql connection object
The sql connection object
 
Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desai
 
Ado
AdoAdo
Ado
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
ADO.net control
ADO.net controlADO.net control
ADO.net control
 
ADO.NETObjects
ADO.NETObjectsADO.NETObjects
ADO.NETObjects
 
Ado.net by Awais Majeed
Ado.net by Awais MajeedAdo.net by Awais Majeed
Ado.net by Awais Majeed
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net Architecture
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdf
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot net
 
Chap14 ado.net
Chap14 ado.netChap14 ado.net
Chap14 ado.net
 
Dapper performance
Dapper performanceDapper performance
Dapper performance
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
 
SQLCLR Tips & Trics
SQLCLR Tips & TricsSQLCLR Tips & Trics
SQLCLR Tips & Trics
 
LECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptxLECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptx
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

For Beginers - ADO.Net

  • 2. Contents • Introduction to ADO.NET • The SqlConnection Object • The SqlCommand Object • Reading Data with the SqlDataReader • Working with Disconnected Data - The DataSet and SqlDataAdapter • Adding Parameters to Commands • Using Stored Procedures
  • 3. Introduction to ADO.NET • ADO.NET is an object-oriented set of libraries that allows you to interact with data sources. • Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file. • 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. These libraries are called Data Providers and are usually named for the protocol or data source type they allow you to interact with. • ADO.NET Data Providers
  • 7. ADO.NET Objects • Connection Object : The connection helps identify the database server, the database name, user name, password, and other parameters that are required for connecting to the data base. A connection object is used by command objects so they will know which database to execute the command on. • Command Object : Use a command object to send SQL statements to the database. A command object uses a connection object to figure out which database to communicate with. • DataReader Object : The data reader object allows you to obtain the results of a SELECT statement from a command object. For performance reasons, the data returned from a data reader is a fast forward-only stream of data. • DataSet Object : DataSet objects are in-memory representations of data. They contain multiple Datatable objects, which contain columns and rows, just like normal database tables. You can even define relations between tables to create parent-child relationships. The DataSet is an object that is used by all of the Data Providers, which is why it does not have a Data Provider specific prefix. • DataAdapter Object : The data adapter fills a DataSet object when reading the data and writes in a single batch when persisting changes back to the database. A data adapter contains a reference to the connection object and opens and closes the connection automatically when reading from or writing to the database. • CommandBuilder : By default dataadapter contains only the select command and it doesn’tcontain insert, update and delete commands. To create insert, update and delete commands for the dataadapter, commandbuilder is used. It is used only to create these commands for the dataadapter and has no other purpose.
  • 8. SqlConnection Object • The connection tells the rest of the ADO.NET code which database it is talking to. It manages all of the low level logic associated with the specific database protocols. • Declare and instantiate the SqlConnection as shown below: SqlConnection conn = new SqlConnection ( "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI"); • ADO.NET Connection String Parameters Parameter Description Name Identifies the server. Could be local machine, machine domain name, or IP Data Source Address. Initial Catalog Database name. Integrated Set to SSPI to make connection with user's Windows login Security User ID Name of user configured in SQL Server. Password Password matching SQL Server User ID.
  • 9. SqlCommand & SqlDataReader Object • SqlCommand object allows you to specify what type of interaction you want to perform with a database. For example, you can do select, insert, modify, and delete commands on rows of data in a database table. • Creating a SqlCommand Object SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn); • 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. • Creating a SqlDataReader Object • Getting an instance of a SqlDataReader is a little different than the way you instantiate other ADO.NET objects. You must call ExecuteReader on a command object, like this: SqlDataReader rdr = cmd.ExecuteReader();
  • 10. SqlCommand Methods • 1) ExecuteReader -Querying Data • Similarly ExecuteNonQuery can be used to • Used to retrieve data records for viewing. It update a record using below query string returns a SqlDataReader object. // prepare command string • Example: string updateString = @" // 1. Instantiate a new command with a query update Categories set CategoryName = 'Other' and connection where CategoryName = 'Miscellaneous'"; SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn); • Similarly ExecuteNonQuery can be used to // 2. Call Execute reader to get query results delete a record using below query string SqlDataReader rdr = cmd.ExecuteReader(); // prepare command string string deleteString = @" delete from Categories • 2) ExecuteNonQuery (Insert/Update/Delete) where CategoryName = 'Other'"; • To insert data into a database, use the ExecuteNonQuery method of the SqlCommand object. 3) ExecuteScalar - Getting Single values // prepare command string • string insertString = @" Used to get count, sum, average, or other insert into Categories aggregated value from a database. (CategoryName, Description) // 1. Instantiate a new command values ('Miscellaneous', 'Whatever doesn''t SqlCommand cmd = new SqlCommand("select fit elsewhere')"; count(*) from Categories", conn); // 1. Instantiate a new command with a query // 2. Call ExecuteNonQuery to send command and connection int count = (int)cmd.ExecuteScalar(); SqlCommand cmd • The query in the SqlCommand constructor = new SqlCommand(insertString, conn); obtains the count of all records from the Categories table. This query will only return a // 2. Call ExecuteNonQuery to send command single value. cmd.ExecuteNonQuery();
  • 11. Connected Example: • Example in attached file to retrieve, insert, update, delete record from data table. Double click on below link to open notepad file. ConnectedExample.txt
  • 12. Working with Disconnected Data • 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: • Open connection • Retrieve data into DataSet • Close connection • and performs the following actions when updating data source with DataSet changes: • Open connection • Write changes from DataSet to data source • 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.
  • 13. Disconnected Example • Example below in text file use DataSet and SqlDataAdapter to get customer records & display in datagrid. Datagrid is editable &changes can be saved using “Update” button. Double click below file to open. DisconnectedEmaple.txt
  • 14. Adding Parameters to Commands • Using parameterized queries is a three step process: 1) Construct the SqlCommand command string with parameters. SqlCommand cmd = new SqlCommand( "select * from Customers where city = @City", conn); 1) Declare a SqlParameter object, assigning values as appropriate. SqlParameter param = new SqlParameter(); param.ParameterName = "@City"; param.Value = inputCity; 3) Assign the SqlParameter object to the SqlCommand object's Parameters property. cmd.Parameters.Add(param); 4) Below is complete console application example double click to open. AddingParameterExample.txt
  • 15. Using Stored Procedures • A stored procedures is a pre-defined, reusable routine that is stored in a database. • SQL Server compiles stored procedures, which makes them more efficient to use. • Therefore, rather than dynamically building queries in your code, you can take advantage of the reuse and performance benefits of stored procedures. • Executing a Stored Procedure // 1. create a command object identifying the stored procedure SqlCommand cmd = new SqlCommand( “<<StoredProcName>>", conn); // 2. set the command object so it knows to execute a stored procedure cmd.CommandType = CommandType.StoredProcedure; • Sending Parameters to Stored Procedures SqlCommand cmd = new SqlCommand( "CustOrderHist", conn); // 2. set the command object so it knows to execute a stored procedure cmd.CommandType = CommandType.StoredProcedure; // 3. add parameter to command, which will be passed to the stored procedure cmd.Parameters.Add( new SqlParameter("@CustomerID", custId)); • The name of the parameter passed as the first parameter to the SqlParameter constructor must be spelled exactly the same as the stored procedure parameter.
  • 16. Stored Procedure Example • Below example uses 2 procedures to get • top 10 expensive products • Customer specific orders Double click to open example below StoredProcedureExample.txt

Editor's Notes

  1. If we were using the OleDb Data Provider to connect to a data source that exposes an OleDb interface, we would use a connection object named OleDbConnection. Similarly, the connection object name would be prefixed with Odbc or Sql for an OdbcConnection object on an Odbc data source or a SqlConnection object on a SQL Server database