0% found this document useful (0 votes)
36 views20 pages

Lectur 4

The document discusses LINQ architecture, ADO.NET, and using the DataGridView for database access. It provides details on LINQ, describing its architecture and how it provides a common query syntax for different data sources. It also describes ADO.NET components and architecture, and how to connect to a database, execute commands, and retrieve results using ADO.NET classes.

Uploaded by

Markos Mathewos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views20 pages

Lectur 4

The document discusses LINQ architecture, ADO.NET, and using the DataGridView for database access. It provides details on LINQ, describing its architecture and how it provides a common query syntax for different data sources. It also describes ADO.NET components and architecture, and how to connect to a database, execute commands, and retrieve results using ADO.NET classes.

Uploaded by

Markos Mathewos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Chapter-4

Database Programming in C#

Points:
 LINQ Architecture
 ADO.NET
 Using the DataGridView for database access

1
LINQ
 The LINQ (Language Integrated Query) is a part of a language
 It was introduced by Microsoft with .NET Framework 3.5 and C# 3.0 and is
available in System.Linq namespace.
 LINQ provides us common query syntax which allows us to query the data from
various data sources.
 That means using a single query we can get or set the data from various data
sources such as SQL Server database, XML documents, ADO.NET Datasets, and
any other in-memory objects such as Collections, Generics, etc.

2
LINQ Architecture

3
LINQ…
 Suppose we are developing a .NET Application and that application requires data from
different data sources.
For example
 The application needs data from SQL Server Database.
 So as a developer in order to access the data from SQL Server Database, we need to
understand ADO.NET and SQL Server-specific syntaxes.
 If the database is Oracle then we need to learn Syntaxs specific to Oracle Database.
 The application also needs data from an XML Document.
 So as a developer in order to work with XML Document, we need to understand XPath and
XSLT queries.
 The application also needs to manipulate the data (objects) in memory such as
List<Products>, List<Orders>, etc.
 So as a developer we should also have to understand how to work with in-memory objects.

4
LINQ…

 LINQ provides a uniform programming model (i.e. common query syntax) which
allows us to work with different data sources but using a standard or unified coding
style.
 As a result, we don’t require to learn different syntaxes to query different data
sources.

5
ADO.NET
 ADO.NET (Active Data Object).NET is a set of classes that comes with the
Microsoft .NET framework to facilitate data access from managed languages.
 ADO.NET has been in existence for a long time and it provides a comprehensive
and complete set of libraries for data access.
 The strength of ADO.NET is firstly that it lets applications access various types of
data using the same methodology.
 If you know how to use ADO.NET to access a SQL Server database then the same
methodology can be used to access any other type of database (like Oracle or MS
Access) by just using a different set of classes.
 Secondly, ADO.NET provides two models for data access: a connected model
where you can keep the connection with the database and perform data access, and
another way is to get all the data in ADO.NET objects that let us perform data
access on disconnected objects.

6
ADO.NET Architecture

7
ADO.NET Components
.NET Framework Data Provider
 The .NET Framework Data Providers are components that have been explicitly
designed for data manipulation and fast, forward-only, read-only access to data.
Core Objects of .NET Framework Data Providers
 Connection: Establishes a connection to a specific data source. The base class for
all Connection objects is the SqlConnection class.
 Command: Executes a command against a data source. Exposes Parameters and
can execute in the scope of a Transaction from a Connection. The base class for all
Command objects is the SqlCommand class.
 DataReader: Reads a forward-only, read-only stream of data from a data source.
The base class for all DataReader objects is the DbDataReader class.
 DataAdapter: Populates a DataSet and resolves updates with the data source. The
base class for all DataAdapter objects is the DbDataAdapter class.

8
ADO.NET Components…
DataSet
 The ADO.NET DataSet is explicitly designed for data access independent of any
data source.
 As a result, it can be used with multiple and differing data sources, used with XML
data, or used to manage data local to the application.
 The DataSet contains a collection of one or more DataTable objects consisting of
rows and columns of data, and also primary key, foreign key, constraint, and
relation information about the data in the DataTable objects.

9
ADO.NET Components…
DataSet…
Use a DataSet to do the following:
 Cache data locally in your application so that you can manipulate it.
 If you only need to read the results of a query, the DataReader is the better choice.
 Remote data between tiers or from an XML Web service.
 Interact with data dynamically such as binding to a Windows Forms control or
combining and relating data from multiple sources.
 Perform extensive processing on data without requiring an open connection to the
data source, which frees the connection to be used by other clients.

10
The following figure shows the ADO.NET objects

11
ADO.net Common Classes under using System.Data.SqlClient;

Class Description
SqlConnection It is used to create SQL Server connection. This class cannot be
inherited.
SqlCommand It is used to execute database queries. This class cannot be
inherited.
SqlDataAdapter It represents a set of data commands and a database connection
that are used to fill the DataSet. This class cannot be inherited.

SqlDataReader It is used to read rows from a SQL Server database. This class
cannot be inherited.
SqlException This class is used to throw SQL exceptions. It throws an
exception when an error is occurred. This class cannot be
inherited.
12
In a typical scenario requiring data access, we need to perform four major tasks:
1. Connecting to the database
2. Passing the request to the database, i.e., a command like select, insert, or
update(CRUD).
3. Getting back the results, i.e., rows and/or the number of rows effected.
4. Storing the result and displaying it to the user.

13
 connection object An object in ADO.NET that allows you to open and execute
commands against a database.
 The following code creates an instance of the SqlConnection object, sets the
connectionString property, and opens a connection to the database:

 Command object is used to call a stored procedure or execute a dynamic SQL


statements (insert, update, delete, and select) .
 The Command’s ExecuteNonQuery method is used to execute nonresult-
returning queries such as an INSERT or UPDATE command.

14
 The following code demonstrates how to execute an insert statement against the
database:
SqlConnection cn = new SqlConnection();
cn.ConnectionString "Server=myServerAddress;Database=myDataBase;UserId=myUsername;
Password=myPassword;";
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Person (FirstName, LastName) VALUES ('Joe', 'Smith')";
cmd.ExecuteNonQuery();
cn.Close();

15
 ExecuteReader method Executes the CommandText against the Connection and returns a DbDataReader.
 A DBDataReader object is a read-only, forward-only cursor connected to the database.
 The following code prints all the records in the Person table to the output window using a
DBDataReader object.
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Server=myServerAddress;Database=myDataBase;User
Id=myUsername;Password=myPassword;";
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Person";
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows) { while (dr.Read())
{ Debug.WriteLine(string.Format("First Name: {0} , Last Name: {1}", dr["FirstName"], dr["LastName"])); }
}
dr.Close();
cn.Close();

16
Continued …
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Person";
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Debug.WriteLine(string.Format("First Name: {0} , Last Name: {1}", dr["FirstName"], dr["LastName"]));
}
}
dr.Close();
cn.Close();

17
DataGridView
• The DataGridView can display data in Bound mode, unbound mode and
Virtual mode .
• Bound mode is suitable for managing data using automatic interaction
with the data store.
• One very common use of the DataGridView control is binding to a table
in a database.
• Unbound mode is suitable for displaying relatively small amounts of data
that you manage programmatically.
• Virtual mode gives you a higher degree of control by allowing you to
wait until a cell is actually being displayed to provide the value it will
contain.

18
The following C# program shows how to bind a SQL Server dataset to a
DataGridView.
1. using System;
20. connection.Open();
2. using System.Data;
21. dataadapter.Fill(ds, "Authors_table");
3. using System.Windows.Forms;
22. connection.Close();
4. using System.Data.SqlClient;
23. dataGridView1.DataSource = ds;
5. namespace WindowsApplication1
24. dataGridView1.DataMember = "Authors_table";
6. {
25. }
7. public partial class Form1 : Form
26. }
8. {
27. }
9. public Form1()
10. {
11. InitializeComponent();
12. }
13. private void button1_Click(object sender, EventArgs e)
14. {
15. string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated
Security=True";
16. string sql = "SELECT * FROM Authors";
17. SqlConnection connection = new SqlConnection(connectionString);
18. SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
19. DataSet ds = new DataSet(); 19
Practical Lab Exercises
 Write create, insert, delete, update (CRUD) code in C# for your respective project
works by defining and manipulating with ADO.NET SQL Server database.
 (Note: perform the same logic for at least three tables or relations from your project
work).

20

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy