0% found this document useful (0 votes)
32 views

Session 7

The document discusses ADO.NET and database programming using ADO.NET. It covers ADO.NET architecture, data providers, datasets, connecting to different data sources, executing commands, parameters, and more in detail over multiple slides.
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)
32 views

Session 7

The document discusses ADO.NET and database programming using ADO.NET. It covers ADO.NET architecture, data providers, datasets, connecting to different data sources, executing commands, parameters, and more in detail over multiple slides.
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/ 37

DCIT 318

PROGRAMMING II

Session 7 – Database Programming Using


ADO.NET
Lecturer: Mr. Paul Ammah, CSD
Contact Information: [email protected]

Department of Computer Science


School of Physical and Mathematical Sciences
2022/2023
ADO.NET
• ADO.NET is a set of classes for database access.
• It is a specification that unifies access to relational
databases, XML files, and other application data.
• The ADO.NET classes are found in System.Data
namespace.
• The full form of ADO.Net is ActiveX® Data Objects
• ADO.Net can be used by any .Net Language

Slide 2
ADO.NET Architecture
• The two main components of ADO.NET for accessing and
manipulating data are
– the .NET Framework data providers
– the DataSet
• A .NET Framework data provider is used for connecting to a
database, executing commands, and retrieving result
• Those results are either:
– processed directly
– placed in a DataSet in order to be exposed to the user as needed
– combined with data from multiple sources
– remoted between tiers.

Slide 3
Data Providers

OLE DB - Object Linking and Embedding Database


ODBC - Open Database Connectivity
Slide 4
Core Objects of .NET Framework Data
Providers

• In addition to the core classes .NET Framework data provider also contains these classes:
• Transaction, CommandBuilder, ConnectionStrngBuilder,
• Parameter, Exception, Error and ClientPErmission

Slide 5
ADO.NET DataSets
• The DataSet is a memory-resident representation of
data that provides a consistent relational
programming model regardless of the data source.
• The methods and objects in a DataSet are consistent
with those in the relational database model.
• DataSet contains a collection of zero or more tables
represented by DataTable objects.

Slide 6
DataSet Object Model

Slide 7
DataSet Object Model cont’d
• The DataTableCollection contains all the DataTable objects in a
DataSet.
• A DataTable is defined in the System.Data namespace and
represents a single table of memory-resident data.
• A collection of rows (DataRow) represented by the
DataRowCollection
• A collection of columns (DataColumn) in a DataTable is
represented by a DataColumnCollection
• A collection of constraints on a DataTable is represented by a
ConstraintCollection
• A DataView enables you to create different views of the data
stored in a DataTable
Slide 8
Retrieving and Modifying Data in ADO.NET

• .NET Framework data providers of ADO.NET allow


you to execute commands as well as to retrieve data
by using a
– DataReader
– DataAdapter

• Updating data involves using


– DataAdapter and DataSet, and Command objects; and it
may also involve using transactions.

Slide 9
Connecting to a Data Source
• Each .NET Framework data provider included with
the .NET Framework has a DbConnection object
– Data Provider for OLE DB includes an OleDbConnection
object
– Data Provider for SQL Server includes a SqlConnection
object
– Data Provider for ODBC includes an OdbcConnection
object
– Data Provider for Oracle includes an OracleConnection
object

Slide 10
Connecting to SQL Server
• The using block in C# automatically disposes of the connection
when the code exits the block, even in the case of an unhandled
exception
• A connection string contains initialization information that is
passed as a parameter from a data provider to a data source. E.g.
“Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword; “

using (SqlConnection connection = new SqlConnection(connectionString))

{
connection.Open();
// Do work here.
}

Slide 11
Connecting to an OLE DB Data Source
// Assumes connectionString is a valid connection string.

using (
OleDbConnection connection = new OleDbConnection(connectionString)
)
{
connection.Open();
// Do work here.
}

Slide 12
Connecting to an ODBC Data Source
// Assumes connectionString is a valid connection string.

using (
OdbcConnection connection = new OdbcConnection(connectionString)
)
{
connection.Open();
// Do work here.
}

Slide 13
Connecting to an Oracle Data Source
// Assumes connectionString is a valid connection string.

using (
OracleConnection connection =
new OracleConnection(connectionString)
)
{
connection.Open();
// Do work here.
}

Slide 14
Commands and Parameters
• After establishing a connection to a data source, you
can execute commands and return results from the
data source using a DbCommand object.
• Create a command for a particular connection using
the CreateCommand method of a DbConnection
object.
• The SQL statement being executed by the command
can be configured using the CommandText property

Slide 15
Executing a Command
• Each .NET Framework data provider has its own
command object that inherits from DbCommand
– Data Provider for OLE DB includes an OleDbCommand
object
– Data Provider for SQL Server includes a SqlCommand
object
– Data Provider for ODBC includes an OdbcCommand object
– Data Provider for Oracle includes an OracleCommand
object

Slide 16
Command Execution Methods & Command
Types
Command Objects expose methods for executing commands based on the type of command
and desired return value as described below:

Command object also supports a CommandType enumeration that specifies how a


command string is interpreted

Slide 17
ExecuteReader Example
public void ReadMyData(string connectionString)
{ //Executes commands that return rows.
string queryString = "SELECT OrderID, CustomerID FROM Orders";
using (
OleDbConnection connection = new OleDbConnection(connectionString)
)
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();

while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + ", " +
reader.GetString(1));
}
// always call Close when done reading.
reader.Close();
}
} Slide 18
ExecuteNonQuery Example
public void InsertRow(string connectionString, string insertSQL)
{
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OdbcCommand command = new OdbcCommand(insertSQL, connection);

// Open the connection and execute the insert command.


try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
Executes commands such as SQL INSERT, DELETE, UPDATE, and SET statements.
Slide 19
ExecuteScalar Example
static public int GetTotalNumberOfRegions(string connString)
{
Int32 count = 0;
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
count = (Int32) cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int) count;
}

Slide 20
Using Parameters
• Command objects use parameters to pass values to
SQL statements or stored procedures, providing type
checking and validation
• Unlike command text, parameter input is treated as a
literal value, not as executable code.
– This behavior helps guard against "SQL injection" attack
• When adding parameters, you must supply a
ParameterDirection property for parameters other
than input parameters.

Slide 21
ParameterDirection

Slide 22
Parameter Placeholders and Data Types
• The syntax for parameter placeholders depends on the data
source.
• The SqlCommand data provider uses named parameters in the
format @parametername
• With an OleDbCommand or OdbcCommand, parameters must be
added to the Parameters collection in the order defined
• You specify the type of a Parameter in a generic manner by
setting the DbType property of the Parameter object to a
particular DbType.
• E.g. DbType:
– Boolean, Binary, DateTime, Date, Decimal, Double, Int16, Int32, Int64,
String, VarNumeric, UInt16, UInt32, UInt64

Slide 23
Parameter Placeholders

Slide 24
Adding Parameters
• Each .NET Framework data provider has its own
command object that inherits from DbParameter
– Data Provider for OLE DB includes an OleDbParameter
object
– Data Provider for SQL Server includes a SqlParameter
object
– Data Provider for ODBC includes an OdbcParameter object
– Data Provider for Oracle includes an OracleParameter
object

Slide 25
Parameter Example
sql = SELECT * FROM Customers WHERE CustomerID = ?

OdbcCommand command = new OdbcCommand(sql,


connection);

OdbcParameter parameter =
new OdbcParameter(“@p1”,OdbcType.Int);

parameter.Value = 20;
parameter.Direction = ParameterDirection.Input;
command.Add(parameter);

OdbcDataReader reader = command.ExecuteReader();

Slide 26
DataReaders
• You can use ADO.NET DataReader to retrieve a read-
only, forward-only stream of data from a database.
• Results are returned as the query executes
• Results are stored in the network buffer on the client
until they are requested using the Read method of
the DataReader.
• Using the DataReader can increase application
performance both by
– retrieving data as soon as it is available,
– and (by default) storing only one row at a time in memory
Slide 27
DbDataReaders
• Each .NET Framework data provider has its own
DbDataReaders
– Data Provider for OLE DB includes an OleDbDataReader
object
– Data Provider for SQL Server includes a SqlDataReader
object
– Data Provider for ODBC includes an OdbcDataReader
object
– Data Provider for Oracle includes an OracleDataReader
object

Slide 28
DbDataReader Example
static void HasRows(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();

SqlDataReader reader = command.ExecuteReader();

if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}

Slide 29
DataAdapters
• A DataAdapter is used to retrieve data from a data
source and populate tables within a DataSet.
• Each .NET Framework data provider has a
DbDataAdapter object
– Data Provider for OLE DB -> OleDbDataAdapter
– Data Provider for SQL Server -> SqlDataAdapter
– Data Provider for ODBC -> OdbcDataAdapter
– Data Provider for Oracle -> OracleDataAdapter

Slide 30
DataAdapter Example
using (connection)
{
// Define the query.
string queryString = "SELECT CategoryName FROM Categories";

// Assumes that connection is a valid OdbcConnection object.


OdbcDataAdapter adapter = new OdbcDataAdapter();

OdbcCommand selectCMD = new OdbcCommand(selectSQL, connection);

adapter.SelectCommand = selectCMD;

DataSet customers = new DataSet();


adapter.Fill(customers, "Customers");
}

A DataAdapter has SelectCommand, InsertCommand, UpdateCommand, DeleteCommand


Properties that can be used to set the commands appropriately
Slide 31
Accessing DataRow From DataTable
OdbcDataAdapter odbcDataAdapter = new OdbcDataAdapter( sqlString, conn );
DataSet studentDataSet = new DataSet();
odbcDataAdapter.Fill(studentDataSet,”students”);

 foreach(
  DataRow studentRow in studentDataSet.Tables[”students"].Rows
) {
     Console.WriteLine($"ID: {studentRow["id"].ToString()}");
     Console.WriteLine($"NAME: {studentRow["name"].ToString()}");
    Console.WriteLine($"GENDER: {studentRow["gender"].ToString()}");
    Console.WriteLine(
$"INDEX NUMBER: {studentRow["index_number"].ToString()}”
);

}
                }

Slide 32
Combining Multiple DataAdapters
• Any number of DataAdapter objects can be used
with a DataSet
• DataRelation and Constraint objects can be added to
the DataSet locally, which enables you to relate data
from dissimilar data sources.

Slide 33
Populating a DataSet from Multiple
DataAdapters
SqlDataAdapter custAdapter = new SqlDataAdapter(
"SELECT * FROM dbo.Customers", customerConnection);

OleDbDataAdapter ordAdapter = new OleDbDataAdapter(


"SELECT * FROM Orders", orderConnection);

DataSet customerOrders = new DataSet();

custAdapter.Fill(customerOrders, "Customers");
ordAdapter.Fill(customerOrders, "Orders");

DataRelation relation = customerOrders.Relations.Add("CustOrders",


customerOrders.Tables["Customers"].Columns["CustomerID"],
customerOrders.Tables["Orders"].Columns["CustomerID"]);

foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows)


{
Console.WriteLine(pRow["CustomerID"]);
foreach (DataRow cRow in pRow.GetChildRows(relation))
Console.WriteLine("\t" + cRow["OrderID"]);
}

Slide 34
Generating Commands with
CommandBuilders
• If your DataTable maps to a single database table,
you can use DbCommandBuilder to build
commands.
• DbCommandBuilder object can automatically
generate the DeleteCommand, InsertCommand, and
UpdateCommand of the DbDataAdapter.
– As a minimum requirement for automatic command
generation, set the SelectCommand property
– The SelectCommand must also return at least one primary
key or unique column

Slide 35
CommandBuilder Objects
• Each .NET Framework data provider has a
DbCommandBuilder object
– Data Provider for OLE DB -> OleDbCommandBuilder
– Data Provider for SQL Server -> SqlCommandBuilder
– Data Provider for ODBC -> OdbcCommandBuilder
– Data Provider for Oracle -> OracleCommandBuilder

Slide 36
Generating Commands with
DbCommandBuilder
OdbcDataAdapter adapter = new OdbcDataAdapter(
"SELECT * FROM dbo.Customers", connection
);

OdbcCommandBuilder builder = new OdbcCommandBuilder(adapter);

Console.WriteLine(builder.GetInsertCommand().CommandText);

Console.WriteLine(builder.GetDeleteCommand().CommandText);

Console.WriteLine(builder.GetUpdateCommand().CommandText);

Slide 37

You might also like