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

Database Connectivity - ASP - Net Lecture 6

ADO.NET is an object-oriented framework that allows applications to interact with data sources. It includes classes like SqlConnection to establish database connections, SqlCommand to execute queries and non-queries, and SqlDataReader to retrieve query results. ADO.NET supports multiple data providers that allow interacting with different data sources like SQL Server, Oracle, and Access.

Uploaded by

djpaul35
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
169 views20 pages

Database Connectivity - ASP - Net Lecture 6

ADO.NET is an object-oriented framework that allows applications to interact with data sources. It includes classes like SqlConnection to establish database connections, SqlCommand to execute queries and non-queries, and SqlDataReader to retrieve query results. ADO.NET supports multiple data providers that allow interacting with different data sources like SQL Server, Oracle, and Access.

Uploaded by

djpaul35
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

Database Connectivity

http://freepdf-books.com
ActiveX Data Objects
j
Microsoft’s data access technologies
Set of classes that provide data access services
ADO.NET
Class Library System.Data

2
http://freepdf-books.com
Introduction
` 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.

3
http://freepdf-books.com
ADO.NET Objects

Object Description
Connection Establishes a connection to a specific data source.
Command Executes a command against
g a data source. Exposes
p
Parameters and can execute within the scope of a
Transaction from a Connection.
DataReader Reads a forward-only, read-only stream of data from a data
source.
DataAdapter Populates a DataSet and resolves updates with the data
source.
DataSet DataSet objects are in-memory representations of data.

4
http://freepdf-books.com
Data Providers
ADO.NET Data Providers are class libraries that allow a common way to interact with
specific
ifi ddata
t sources or protocols.
t l The
Th library
lib API
APIs have
h prefixes
fi th
thatt indicate
i di t which
hi h
provider they support.

Provider Name API Prefix Data Source Description


Data Sources with an ODBC interface. Normally
ODBC Data Provider Odbc
older data bases.
Data Sources
So rces that expose
e ose an OleDb interface
interface, ii.e.
e
OleDb Data Provider OleDb
Access or Excel.
Oracle Data Provider Oracle For Oracle Databases.
SQL Data
D Provider
P id S l
Sql F iinteracting
For i with
i h Mi
Microsoft
f SQL SServer.

5
http://freepdf-books.com
Sql Data Provider

6
http://freepdf-books.com
The SqlConnection Object
` To interact with a database, you must have a connection to it.
` The connection helps identify the database server,
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.

SqlConnection conn = new SqlConnection(


SqlConnection(
"Data
Data Source=(local);Initial
Source (local);Initial Catalog=Northwind;Integrated
Catalog=
Catalog Northwind;Integrated Security
Security=SSPI"
SSPI );

7
http://freepdf-books.com
SqlConnection - Parameter Names
ADO.NET Connection Strings contain certain key/value pairs for specifying how to
make a database connection. They include the location, name of the database, and
security credentials.
d l
Connection
String Parameter Description
Name

Identifies the server. Could be local machine, machine domain


Data Source
name or IP Address
name, Address.

Initial Catalog Database 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.
8
http://freepdf-books.com
The SqlCommand Object
` Command object is used to send SQL statements to the
database.
` A command object uses a connection object to figure out
which database to communicate with.

SqlCommand cmd = new SqlCommand


SqlCommand(“SELECT
(“SELECT
CategoryName FROM Categories", conn);
conn);

9
http://freepdf-books.com
Using SqlConnection Object
using System; // 4. Use the connection
using System.Data;
// get query results
usingg System.Data.SqlClient;
y q SqlDataReader rdr = cmd.ExecuteReader();

class SqlConnectionDemo // print the CustomerID of each record


{ while (rdr.Read())
static void Main() {
{ Console.WriteLine(rdr[0]);
// 1.
1 Instantiate
I t ti t the
th connection
ti }
SqlConnection conn = new SqlConnection
SqlConnection(( }
"Data Source=(local);Initial finally
Catalog=Northwind;Integrated Security=SSPI"); "); {
// close the reader
if (rdr != null)
try {
{ rdr.Close();
// 2. Open the connection }
conn.Open();
// 5. Close the connection
// 3. Pass the connection to a command object if (conn != null)
SqlCommand cmd = new SqlCommand("
SqlCommand("select * {
from Customers", ", conn);
conn); conn.Close();
}
}
}
}

10
http://freepdf-books.com
SqlCommand: Querying Data
// 1. Instantiate a new command with a query and connection
SqlCommand
q cmd = new SqlCommand(“SELECT
q (
CategoryName FROM Categories", conn);

// 2.
2 Call
C ll Execute
E t reader
d tot gett query results
lt
SqlDataReader rdr = cmd.ExecuteReader();

` Results some rows that you can iterate through using


rdr.Read()
rdr.Read () method

11
http://freepdf-books.com
SqlCommand: Inserting Data
// prepare command string
string insertString = @"
INSERT INTO Categories
(CategoryName, Description)
VALUES ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";

// 1. Instantiate a new command with a query and connection


SqlCommand cmd = new SqlCommand(insertString, conn);

// 2. Call ExecuteNonQuery to send command


int affectedRows = cmd.ExecuteNonQuery();

` Updates the Database table and returns the number of


rows affected
12
http://freepdf-books.com
SqlCommand: Updating Data
// prepare command string
string updateString = @"
UPDATE Categories
SET CategoryName = 'Other'
WHERE CategoryName = 'Miscellaneous'";

// 1. Instantiate a new command with command text only


SqlCommand cmd = new SqlCommand(updateString,
conn););

// 2. Call ExecuteNonQuery to send command


cmd.ExecuteNonQuery();
Q y();

` Updates the Database table and returns the number of rows


affected

13
http://freepdf-books.com
SqlCommand: Deleting Data
// prepare command string
string deleteString = @"delete from Categories where CategoryName = 'Other'";

// 1. Instantiate a new command


SqlCommand cmd = new SqlCommand();

// 2. Set the CommandText property


cmd.CommandText = deleteString;

// 33. SSet the


h Connection
C i property
cmd.Connection = conn;

// 44. Call ExecuteNonQuery to send command


cmd.ExecuteNonQuery();

` Updates
p the Database table and returns the number of rows affected

14
http://freepdf-books.com
SqlCommand: Getting Single Values
// 1. Instantiate a new command
SqlCommand cmd = new SqlCommand(
SqlCommand("select
select
count(*) from Categories", conn);

// 2. Call ExecuteNonQuery to send command


int count = (int)cmd.ExecuteScalar();

15
http://freepdf-books.com
The SqlDataReader Object
` Many data operations require that you only get a stream
of data for reading.
g
` The data reader object allows you to obtain the results of
a SELECT statement from a command object.
` F performance
For f reasons, the
h ddata returned
d ffrom a data
d
reader is a fast forward-only stream of data. This means
that you can only pull the data from the stream in a
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.
` This is good for speed, but if you need to manipulate data,
then a DataSet is a better object to work with.

16
http://freepdf-books.com
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


cmd.ExecuteReader();
();

The ExecuteReader method of the SqlCommand object,


cmdd returns
t a SqlDataReader
S lD t R d instance.
i t C ti a
Creating
SqlDataReader with the new operator doesn't do
anything
y g for you.
y

17
http://freepdf-books.com
SqlDataReader: ReadingData
The typical method of reading from the data stream returned by
the SqlDataReader is to iterate through each row with a while
loop.
loop
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) { // get the results of each column
string contact = (string)rdr["ContactName"];
string company = (string)rdr["CompanyName"];
string
i city
i = ((string)rdr["City"];
i ) d ["Ci "]
// print out the results
Response.Write(contact + " " + city + " " + company);
}
You can also access table column by their subscript as:
string
i contact = (string)rdr[0];
( i ) d [0] and d so on…
18
http://freepdf-books.com
SqlDataReader : Finishing Up
try
{
// data access code
}
finally
{
// close the reader
if (rdr != null)
{
rdr Close();
rdr.Close();
}
// close the connection too
}
19
http://freepdf-books.com
The End.

20
http://freepdf-books.com

You might also like