Professional Documents
Culture Documents
11 Data Access Part I-1
11 Data Access Part I-1
ADO.NET Fundamentals
Core Concepts
1
Introduction
• ADO.NET
– is a technology that .NET applications use to communicate
with a database (data source in general)
– is a family of objects that provides the above functionality
2
ADO.NET and Data Management
3
Role of Database
• Business software example
• Hierarchical set of related information
– List of customers
– List of products
– List of sales
– Relational model representation
• Problems of State
– Stateless protocol
– Continuously running application –Just an illusion
– Modify retrieved information: identification of record ?
5
Introducing ADO.NET
• DataSet
– A cache of information that has been queried from db.
– Disconnected
– Can store more than one table
– Can store relationships
• Answer questions easily: “What product did Joe Smith
order”
• Disconnected Access
– Previous tech – live connections
– Problem: Limited number of db connections
– Copy of information is made
– Connection is closed
– Reconnect to commit changes
• XML Integration
– As an XML document
– XML manipulation
6
SQL Server Express Edition
• Free data engine
• Free to distribute
• Limitations
– 1 CPU
– 1 GB RAM
– Db 4GB
– Graphical tools missing
7
Pubs Database
• By default no databases are
installed in SQL Server Express
edition.
• The scripts of Pubs database
can be executed to create the
Pubs database.
8
Browsing and Modifying Databases in Visual Studio
1. SQL Server Management Studio
2. Enterprise Manager
3. Visual Studio: Server Explorer
– Data Connections Node
• Existing dbs
• New db
9
Show Edit Table Data
10
SQL Basics
• To design an efficient database application you need to
understand the basic concepts of SQL.
11
Running Queries in Visual Studio
12
Sample Select Statement
• SELECT * FROM Authors
– * --- Slowdown
– FROM clause - Put some limit
– WHERE Clause - Put some limit
–
13
Improving Select Statement
• SELECT au_lname, au_fname
FROM Authors WHERE
State=‘MI’ ORDER BY au_lname
• TOP Clause
14
String Matching with Like Operator
SELECT stor_id, stor_name,
stor_address, city, state, zip
FROM stores
WHERE (stor_name LIKE 'B%')
15
Aggregate Queries
• Avg
• Sum
• Min
• Max
• Count
16
SQL Update Statement
• UPDATE [table] SET [update_expression] WHERE
[search_condition]
17
SQL Insert Statement
• INSERT INTO [table]
([column_list]) VALUES
([value_list])
• Required fields
18
Auto-Increment Fields
• Automatically incrementing identity column
– Assigns a unique value to a specified column when insert
operation is performed.
19
SQL Delete Statement
• DELETE FROM [table] WHERE [search_condition]
• Cascaded Delete
20
ADO.NET Basics
• Set of core objects divided into two groups
– Objects used to contain and maintain data
– Objects used to connect to a specific data source
• ADO.NET Providers
– Each set of data interaction objects is called an ADO.NET
provider
– Customized for best performance
• SQL Server TDS protocol
– Provider objects derive from same base classes, implement
same interfaces, provide same basic set of methods and
properties (+ additional )
21
Providers
• SQL Server provider
– Provides optimized access to
SQL Server 7 or later
• OLEDB Provider
– Access to any data source that
has OLE DB driver
• Oracle Provider
– Optimized access to Oracle 8i
or later
• ODBC Provider
– Access to data source with
ODBC driver
22
Data Namespaces
23
Data Provider Objects
• It is possible to add tables and data by hand in a data object.
• Code similarity
– Externally equivalent
– Code translation
• Differences:
– Namespace
– ADO.NET data access objects
– Internally different
24
Direct Data Access
• Easiest way to access data is to perform db operations directly
• Traditional ADO programming
• To retrieve information
• Create Connection, Command and DataReader objects.
• Use DataReader to retrieve information from db, and display it
on a web form
• Close connection
• Send the page to user.
– No live connection between the information seen by user and
the db
– ADO.NET objects are destroyed
25
Direct Data Access
• To add or update information
– Create Connection and Command objects
– Execute the Command (with SQL statement)
26
Importing Namespaces
– Imports System.Data
– Imports System.Data.SqlClient
– Imports System.Data
– Imports System.Data.OracleClient
– Imports Oracle.DataAccess.Client
27
Creating Connection
• Limited in number
28
Connection String
Dim myConn As New SqlConnection( )
myConn.ConnectionString=“Data Source=localhost; Initial
Catalog=Pubs; Integrated Security=SSPI”
Default instance
Named instance
29
Windows Authentication
• Can be configured using Enterprise Manager or Management
Studio
30
Connection String Tips
• Shared by all application code
• Where to store it?
31
Making the Connection
32
Defining a Select Command
Dim cmd As New OracleCommand
cmd .Connection=myConn
cmd.CommandText=“SELECT * FROM Authors”
Alternate syntax
33
Using a Command with DataReader
• DataReader uses live connection and should be closed quickly.
• Fast-forward-only read-only access
• Better performance than DS
• No way to move back
myConn.Open( )
myReader.Read( )
myReader.Close( )
Conn.Close( )
34
Author Browser
35
Filling List Box
Partial Class AuthorBrowser
Inherits System.Web.UI.Page
WebConfigurationManager.ConnectionStrings("Pubs").Connection
String
36
Conn is opened inside error
handling block.
Code for reading data uses loop.
Listbox is set to use ViewState
37
Retrieving Record
39
Enhancing the Author Page
• Enhancing the previous example
40
Author Manager
41
Selecting a List Item
42
Fields of Selected Author’s Record
43
lstAuthor_SelectedIndexChanged
44
Create New
45
Insert New
46
Error Inserting Record!
47
Successful Insertion
48
Dynamically Generated Insert Statement
• Insert New button triggers the
ADO.NET code that inserts
finished record using a
dynamically generated Insert
statement.
49
Creating More Robust Commands
• Using dynamically pasted-together SQL string has potentially
serious drawbacks
– Users may accidentally enter characters that will effect
SQL statement
– Users might deliberately enter characters that will effect
SQL statement (SQL Injection Attack)
• Orders returned by other customers
• Deleting records in other tables
• xp_cmdshell
51
Parameterization Variations
• SQL server uses a named parameter approach, it does not
matter the parameters order, but each parameter name requires
a "@" prefix.
52
Parameterization Variations
• Oracle uses a similar approach, but a different prefix, since it
expects a ":" prefix.
53
Rewriting Insert Code with Para Command
cmd.Parameters.AddWithValue("@au_id", txtID.Text)
cmd.Parameters.AddWithValue("@au_fname", txtFirstName.Text)
cmd.Parameters.AddWithValue("@au_Lname", txtLastName.Text)
cmd.Parameters.AddWithValue("@phone", txtPhone.Text)
cmd.Parameters.AddWithValue("@address", txtAddress.Text)
cmd.Parameters.AddWithValue("@city", txtCity.Text)
cmd.Parameters.AddWithValue("@state", txtState.Text)
cmd.Parameters.AddWithValue("@zip", txtZip.Text)
cmd.Parameters.AddWithValue("@contract", Val(chkContract.Checked))
54
Updating a Record
55
Update – Bug
56
Deleting a Record
Dim deleteSQL As String
deleteSQL = "DELETE FROM Authors WHERE au_id=@au_id"
“Destructive tasks
are comparatively
easy”
57
References
Textbook: Beginning ASP.NET 4.0
Chapter 14
Parameterized Queries
http://weblogs.asp.net/cibrax/archive/2006/09/28/Parameterized-
Queries-_2800_Oracle_2C00_-SQLServer_2C00_-OleDb_2900_.aspx
Overview of ADO.NET
http://msdn.microsoft.com/en-us/library/h43ks021(v=VS.71).aspx
ADO.NET Architecture
http://msdn.microsoft.com/en-us/library/27y4ybxw(v=VS.71).aspx
58