SlideShare ist ein Scribd-Unternehmen logo
1 von 18
• Understanding Databases
• Configuring, Browsing & Modifying
  Databases in Visual Studio
• SQL Basics
• The Data Provider Model
• Direct Data Access
   • Creating Connection
   • Select, Insert, Delete, Update Records
• Disconnected Data Access
    • Selecting Multiple Tables
    • Defining Relationships
The most common way to manage data is to use a
database. A typical web application is often
just a thin user interface shell on top of
sophisticated data-driven code that reads and
writes information from a database.

In a relational database model information is
stored in the form of tables. SQL Server, Oracle,
and Microsoft Access are examples of relational
database management system.
If you‟re using a full version of SQL Server, you‟ll probably
use a graphical tool such as SQL Server Management
Studio to create and manage your databases.

You can perform many of the same tasks using Visual
Studio‟s Server Explorer Window. Click View ➤ Server
Explorer to show it. Using the Data Connections node in
the Server Explorer, you can connect to existing
databases or create new ones.

Right-click the Data Connections node, and choose Add
Connection. If the Choose Data Source window appears,
select Microsoft SQL Server and then click Continue.
SELECT [columns] FROM [tables] WHERE [search_condition]
ORDER BY [order_expression ASC | DESC]

SELECT au_lname, au_fname FROM Authors WHERE State='CA'
ORDER BY au_lname ASC

SELECT * FROM Sales WHERE ord_date < '2000/01/01' AND
ord_date > '1987/01/01„

SELECT * FROM Stores WHERE stor_name LIKE 'B%„ or „%S‟

SELECT COUNT(*) FROM Authors

UPDATE Authors SET phone='408 496-2222' WHERE au_id='172-
32-1176„

INSERT INTO Authors (au_id, au_lname, au_fname, zip, contract)
VALUES ('998-72-3566', 'Khan', 'John', 84152, 0)

DELETE FROM Authors WHERE au_id='172-32-1176'
ADO.NET relies on the functionality in a small set of
core classes.

You can divide these classes into two groups:

Data Containers that are used to contain and manage
data (such as DataSet, DataTable, DataRow, and
DataRelation)

Data Providers that are used to connect to a specific
data source (such as Connection, Command, and
DataReader).
The SQL Server data provider is designed to work with
SQL Server. The classes you‟ll use fall into three key
namespaces
The most straightforward way to interact with a database
is to use direct data access. You use commands to
query, insert, update, and delete information.

When you query data with direct data access, you don‟t
keep a copy of the information in memory. Instead, you
work with it for a brief period of time while the database
connection is open, and then close the connection as
soon as possible.

The direct data model is well suited to ASP.NET web
pages, which don‟t need to keep a copy of their data in
memory for long periods of time because a page
typically has a lifetime of only a few seconds.
1. Create Connection, Command, and DataReader
   objects.
2. Use the DataReader to retrieve information from the
   database, and display it in a control on a web form.
3. Close your connection.
4. Send the page to the user. At this point, the
   information your user sees and the information in the
   database no longer have any connection, and all the
   ADO.NET objects have been destroyed.

To add or update information, follow these steps:
1. Create new Connection and Command objects.
2. Execute the Command (with the appropriate SQL
   statement).
Before you can retrieve or update data, you need to
make a connection to the data source.

Generally, connections are limited to some fixed number,
and if you exceed that number (either because you run
out of licenses or because your database server can‟t
accommodate the user load), attempts to create new
connections will fail. For that reason, you should try to
hold a connection open for as short a time as possible.

You should also write your database code inside a
try/catch error handling structure so you can respond if
an error does occur, and make sure you close the
connection even if you can‟t perform all your work.
When creating a Connection object, you need to specify a
value for its ConnectionString property. This ConnectionString
defines all the information the computer needs to find the data
source, log in, and choose an initial database.

SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = "Data Source=localhost;" +
"Initial Catalog=Pubs;Integrated Security=SSPI";

You can connect directly to any database file, even if
it‟s not in the master list of databases
myConnection.ConnectionString = @"Data Source
=localhostSQLEXPRESS;" + @"User Instance =True;
AttachDBFilename= |DataDirectory|Northwind.mdf;" +
"Integrated Security=True";

|DataDirectory| automatically points to the App_Data folder
Initial catalog: This is the name of the database that this connection will
be accessing. It’s only the “initial” database because you can change it
later by using the Connection.ChangeDatabase() method.

Integrated security: This indicates you want to connect to SQL Server
using the Windows user account that‟s running the web page code,
provided you supply a value of SSPI (which stands for Security Support
Provider Interface). Alternatively, you can supply a user ID and
password that‟s defined in the database for SQL Server authentication,
although this method is less secure and generally discouraged.

ConnectionTimeout: This determines how long your code will wait, in
seconds, before generating an error if it cannot establish a database
connection. Our example connection string doesn‟t set the
ConnectionTimeout, so the default of 15 seconds is used. You can use
0 to specify no limit, but this is a bad idea. This means that,
theoretically, the code could be held up indefinitely while it attempts
to contact the server.
<configuration>
<connectionStrings>
<add name="Pubs" connectionString=
"Data Source=localhost;Initial Catalog=Pubs;Integrated
Security=SSPI"/>
</connectionStrings>
...
</configuration>

string connectionString =
WebConfigurationManager.ConnectionStrings["Pubs"].Con
nectionString;

SqlConnection myConnection = new
SqlConnection(connectionString);
string connectionString =
WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
try {
myConnection.Open();
lblInfo.Text = "<b>Server Version:</b> " + myConnection.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " +
myConnection.State.ToString();
}
catch (Exception err)
{
// Handle an error by displaying the information.
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
finally{
myConnection.Close();
lblInfo.Text += "<br /><b>Now Connection Is:</b> ";
lblInfo.Text += myConnection.State.ToString();
}
string connectionString =
WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
try {
using (myConnection)
{
// Try to open the connection.
myConnection.Open();
lblInfo.Text = "<b>Server Version:</b> " + myConnection.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " +
myConnection.State.ToString();
} }
catch (Exception err)
{
// Handle an error by displaying the information.
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
lblInfo.Text += "<br /><b>Now Connection Is:</b> ";
lblInfo.Text += myConnection.State.ToString();
string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try{
con.Open();
reader = cmd.ExecuteReader();
     while (reader.Read()) {
     ListItem newItem = new ListItem();
     newItem.Text = reader["au_lname"] + ", " + reader["au_fname"];
     newItem.Value = reader["au_id"].ToString();
     lstAuthor.Items.Add(newItem);}
reader.Close(); }
catch (Exception err)
 {
lblResults.Text = "Error reading list of names. ";
lblResults.Text += err.Message; }
finally
{
con.Close();
}
When you use disconnected data access, you keep a copy of
your data in memory using the DataSet. You connect to the
database just long enough to fetch your data and dump it into
the DataSet, and then you disconnect immediately.
Reasons to use the DataSet to hold onto data in memory:

• You need to do something time-consuming with the data
• You want to use ASP.NET data binding to fill a web control
  (like a GridView) with your data.
• You want to navigate backward and forward through your
  data while you‟re processing it.
• You want to navigate from one table to another.
• You want to save the data to a file for later use.

Weitere ähnliche Inhalte

Was ist angesagt?

ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
Anekwong Yoddumnern
 
Database programming in vb net
Database programming in vb netDatabase programming in vb net
Database programming in vb net
Zishan yousaf
 
For Beginners - Ado.net
For Beginners - Ado.netFor Beginners - Ado.net
For Beginners - Ado.net
Tarun Jain
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to ado
Harman Bajwa
 

Was ist angesagt? (20)

ADO.NET
ADO.NETADO.NET
ADO.NET
 
Ado.net
Ado.netAdo.net
Ado.net
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Ado.net
Ado.netAdo.net
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 Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Database programming in vb net
Database programming in vb netDatabase programming in vb net
Database programming in vb net
 
Ado .net
Ado .netAdo .net
Ado .net
 
For Beginners - Ado.net
For Beginners - Ado.netFor Beginners - Ado.net
For Beginners - Ado.net
 
Database Connection
Database ConnectionDatabase Connection
Database Connection
 
Ado
AdoAdo
Ado
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and Retrieval
 
Chap14 ado.net
Chap14 ado.netChap14 ado.net
Chap14 ado.net
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to ado
 
ODI User and Security
ODI User and Security ODI User and Security
ODI User and Security
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.net
 
Grid Vew Control VB
Grid Vew Control VBGrid Vew Control VB
Grid Vew Control VB
 
Grid View Control CS
Grid View Control CSGrid View Control CS
Grid View Control CS
 

Andere mochten auch (7)

data controls in asp.net
data controls in asp.netdata controls in asp.net
data controls in asp.net
 
Chapter 18
Chapter 18Chapter 18
Chapter 18
 
Chapter 19
Chapter 19Chapter 19
Chapter 19
 
Work with data in ASP.NET
Work with data in ASP.NETWork with data in ASP.NET
Work with data in ASP.NET
 
Chapter 26
Chapter 26Chapter 26
Chapter 26
 
Chapter 25
Chapter 25Chapter 25
Chapter 25
 
Data controls ppt
Data controls pptData controls ppt
Data controls ppt
 

Ähnlich wie Chapter 14

Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
Madhuri Kavade
 
Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)
Mubarak Hussain
 
LECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptxLECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptx
AOmaAli
 
Connected data classes
Connected data classesConnected data classes
Connected data classes
aspnet123
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
Sisir Ghosh
 

Ähnlich wie Chapter 14 (20)

Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#
 
Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)
 
Ado
AdoAdo
Ado
 
Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptx
 
LECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptxLECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptx
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Connected data classes
Connected data classesConnected data classes
Connected data classes
 
WEB PROGRAMMING USING ASP.NET
WEB PROGRAMMING USING ASP.NETWEB PROGRAMMING USING ASP.NET
WEB PROGRAMMING USING ASP.NET
 
unit 3.docx
unit 3.docxunit 3.docx
unit 3.docx
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptx
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdf
 
PPT temp.pptx
PPT temp.pptxPPT temp.pptx
PPT temp.pptx
 
Ado Presentation
Ado PresentationAdo Presentation
Ado Presentation
 
6 database
6 database 6 database
6 database
 

Mehr von application developer (20)

Chapter 23
Chapter 23Chapter 23
Chapter 23
 
Assignment
AssignmentAssignment
Assignment
 
Next step job board (Assignment)
Next step job board (Assignment)Next step job board (Assignment)
Next step job board (Assignment)
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Week 3 assignment
Week 3 assignmentWeek 3 assignment
Week 3 assignment
 
Chapter 13
Chapter 13Chapter 13
Chapter 13
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Chapter 10
Chapter 10Chapter 10
Chapter 10
 
C # test paper
C # test paperC # test paper
C # test paper
 
Chapter 9
Chapter 9Chapter 9
Chapter 9
 
Chapter 8 part2
Chapter 8   part2Chapter 8   part2
Chapter 8 part2
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Week 1 Assignment Q2 Solution
Week 1 Assignment Q2 SolutionWeek 1 Assignment Q2 Solution
Week 1 Assignment Q2 Solution
 
Week 1 assignment q2
Week 1 assignment q2Week 1 assignment q2
Week 1 assignment q2
 
Week 1 Assignment Q1 Solution
Week 1 Assignment Q1 SolutionWeek 1 Assignment Q1 Solution
Week 1 Assignment Q1 Solution
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Chapter 14

  • 1. • Understanding Databases • Configuring, Browsing & Modifying Databases in Visual Studio • SQL Basics • The Data Provider Model • Direct Data Access • Creating Connection • Select, Insert, Delete, Update Records • Disconnected Data Access • Selecting Multiple Tables • Defining Relationships
  • 2. The most common way to manage data is to use a database. A typical web application is often just a thin user interface shell on top of sophisticated data-driven code that reads and writes information from a database. In a relational database model information is stored in the form of tables. SQL Server, Oracle, and Microsoft Access are examples of relational database management system.
  • 3. If you‟re using a full version of SQL Server, you‟ll probably use a graphical tool such as SQL Server Management Studio to create and manage your databases. You can perform many of the same tasks using Visual Studio‟s Server Explorer Window. Click View ➤ Server Explorer to show it. Using the Data Connections node in the Server Explorer, you can connect to existing databases or create new ones. Right-click the Data Connections node, and choose Add Connection. If the Choose Data Source window appears, select Microsoft SQL Server and then click Continue.
  • 4.
  • 5. SELECT [columns] FROM [tables] WHERE [search_condition] ORDER BY [order_expression ASC | DESC] SELECT au_lname, au_fname FROM Authors WHERE State='CA' ORDER BY au_lname ASC SELECT * FROM Sales WHERE ord_date < '2000/01/01' AND ord_date > '1987/01/01„ SELECT * FROM Stores WHERE stor_name LIKE 'B%„ or „%S‟ SELECT COUNT(*) FROM Authors UPDATE Authors SET phone='408 496-2222' WHERE au_id='172- 32-1176„ INSERT INTO Authors (au_id, au_lname, au_fname, zip, contract) VALUES ('998-72-3566', 'Khan', 'John', 84152, 0) DELETE FROM Authors WHERE au_id='172-32-1176'
  • 6. ADO.NET relies on the functionality in a small set of core classes. You can divide these classes into two groups: Data Containers that are used to contain and manage data (such as DataSet, DataTable, DataRow, and DataRelation) Data Providers that are used to connect to a specific data source (such as Connection, Command, and DataReader).
  • 7. The SQL Server data provider is designed to work with SQL Server. The classes you‟ll use fall into three key namespaces
  • 8. The most straightforward way to interact with a database is to use direct data access. You use commands to query, insert, update, and delete information. When you query data with direct data access, you don‟t keep a copy of the information in memory. Instead, you work with it for a brief period of time while the database connection is open, and then close the connection as soon as possible. The direct data model is well suited to ASP.NET web pages, which don‟t need to keep a copy of their data in memory for long periods of time because a page typically has a lifetime of only a few seconds.
  • 9. 1. Create Connection, Command, and DataReader objects. 2. Use the DataReader to retrieve information from the database, and display it in a control on a web form. 3. Close your connection. 4. Send the page to the user. At this point, the information your user sees and the information in the database no longer have any connection, and all the ADO.NET objects have been destroyed. To add or update information, follow these steps: 1. Create new Connection and Command objects. 2. Execute the Command (with the appropriate SQL statement).
  • 10.
  • 11. Before you can retrieve or update data, you need to make a connection to the data source. Generally, connections are limited to some fixed number, and if you exceed that number (either because you run out of licenses or because your database server can‟t accommodate the user load), attempts to create new connections will fail. For that reason, you should try to hold a connection open for as short a time as possible. You should also write your database code inside a try/catch error handling structure so you can respond if an error does occur, and make sure you close the connection even if you can‟t perform all your work.
  • 12. When creating a Connection object, you need to specify a value for its ConnectionString property. This ConnectionString defines all the information the computer needs to find the data source, log in, and choose an initial database. SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = "Data Source=localhost;" + "Initial Catalog=Pubs;Integrated Security=SSPI"; You can connect directly to any database file, even if it‟s not in the master list of databases myConnection.ConnectionString = @"Data Source =localhostSQLEXPRESS;" + @"User Instance =True; AttachDBFilename= |DataDirectory|Northwind.mdf;" + "Integrated Security=True"; |DataDirectory| automatically points to the App_Data folder
  • 13. Initial catalog: This is the name of the database that this connection will be accessing. It’s only the “initial” database because you can change it later by using the Connection.ChangeDatabase() method. Integrated security: This indicates you want to connect to SQL Server using the Windows user account that‟s running the web page code, provided you supply a value of SSPI (which stands for Security Support Provider Interface). Alternatively, you can supply a user ID and password that‟s defined in the database for SQL Server authentication, although this method is less secure and generally discouraged. ConnectionTimeout: This determines how long your code will wait, in seconds, before generating an error if it cannot establish a database connection. Our example connection string doesn‟t set the ConnectionTimeout, so the default of 15 seconds is used. You can use 0 to specify no limit, but this is a bad idea. This means that, theoretically, the code could be held up indefinitely while it attempts to contact the server.
  • 14. <configuration> <connectionStrings> <add name="Pubs" connectionString= "Data Source=localhost;Initial Catalog=Pubs;Integrated Security=SSPI"/> </connectionStrings> ... </configuration> string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].Con nectionString; SqlConnection myConnection = new SqlConnection(connectionString);
  • 15. string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString; SqlConnection myConnection = new SqlConnection(connectionString); try { myConnection.Open(); lblInfo.Text = "<b>Server Version:</b> " + myConnection.ServerVersion; lblInfo.Text += "<br /><b>Connection Is:</b> " + myConnection.State.ToString(); } catch (Exception err) { // Handle an error by displaying the information. lblInfo.Text = "Error reading the database. "; lblInfo.Text += err.Message; } finally{ myConnection.Close(); lblInfo.Text += "<br /><b>Now Connection Is:</b> "; lblInfo.Text += myConnection.State.ToString(); }
  • 16. string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString; SqlConnection myConnection = new SqlConnection(connectionString); try { using (myConnection) { // Try to open the connection. myConnection.Open(); lblInfo.Text = "<b>Server Version:</b> " + myConnection.ServerVersion; lblInfo.Text += "<br /><b>Connection Is:</b> " + myConnection.State.ToString(); } } catch (Exception err) { // Handle an error by displaying the information. lblInfo.Text = "Error reading the database. "; lblInfo.Text += err.Message; } lblInfo.Text += "<br /><b>Now Connection Is:</b> "; lblInfo.Text += myConnection.State.ToString();
  • 17. string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(selectSQL, con); SqlDataReader reader; try{ con.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { ListItem newItem = new ListItem(); newItem.Text = reader["au_lname"] + ", " + reader["au_fname"]; newItem.Value = reader["au_id"].ToString(); lstAuthor.Items.Add(newItem);} reader.Close(); } catch (Exception err) { lblResults.Text = "Error reading list of names. "; lblResults.Text += err.Message; } finally { con.Close(); }
  • 18. When you use disconnected data access, you keep a copy of your data in memory using the DataSet. You connect to the database just long enough to fetch your data and dump it into the DataSet, and then you disconnect immediately. Reasons to use the DataSet to hold onto data in memory: • You need to do something time-consuming with the data • You want to use ASP.NET data binding to fill a web control (like a GridView) with your data. • You want to navigate backward and forward through your data while you‟re processing it. • You want to navigate from one table to another. • You want to save the data to a file for later use.