sesión 05 - ado.net

50
Desarrollo de aplicaciones .NET Eduardo Rivera Alva - MCTS.Net ([email protected]) Desarrollo de Aplicaciones Capítulo 05 ADO.Net

Upload: eriveraa

Post on 14-Oct-2014

4.454 views

Category:

Documents


5 download

DESCRIPTION

Sesión 05 del Curso Desarrollo de Aplicaciones .NET (2007-II) - Universidad San Ignacio de Loyola (USIL)

TRANSCRIPT

Page 1: Sesión 05 - ADO.Net

Desarrollo de aplicaciones .NETEduardo Rivera Alva - MCTS.Net ([email protected])

Desarrollo de Aplicaciones

Capítulo 05

ADO.Net

Page 2: Sesión 05 - ADO.Net

Desarrollo de aplicaciones .NETEduardo Rivera Alva - MCTS.Net ([email protected])

Agenda

• Repaso sesión anterior.

• ADO.Net– Introducción

– Arquitectura

– Data Providers• Connection

• Command

• DataReader

• DataAdapter

– DataSet

– LINQ

– Clases Comunes

– Escenario Conectado

– Escenario Desconectado

– Ejemplos

• Que veremos la próxima sesión?

Page 3: Sesión 05 - ADO.Net

Desarrollo de aplicaciones .NETEduardo Rivera Alva - MCTS.Net ([email protected])

Repaso sesión anterior

• Arrays

– Uni-dimensionales, Multidimensionales

– Estructura interna

– Arrays tipo valor y tipo referencia

– Iteración

• Colecciones

– ArrayList

• Ver diapositivas previas.

Page 4: Sesión 05 - ADO.Net

ADO.Net

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Referencias

1. Understanding .NET. Caps. 6 (Accesing Data: ADO.Net)

2. NET Framework Developer’s Guide: ADO.NET (http://msdn2.microsoft.com/en-

us/library/e80y5yhx(VS.80).aspx)

3. Apress Pro ADO.NET.2.0.

Page 5: Sesión 05 - ADO.Net

ADO.Net

• Idea de acceso a datos universal

– Comunicación entre los lenguajes de programación y las bases de

datos o fuentes de datos.

– Modelo de programación uniforme mediante una API estándar.

– Implementaciones especializadas para las fuentes de datos

(providers).

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 6: Sesión 05 - ADO.Net

ADO.Net

• Qué propone NET Framework?

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 7: Sesión 05 - ADO.Net

ADO.Net

• ADO.NET

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

SQL-data

MS SQL Server, Oracle,

Jet, Foxpro, ...

SQL Server

Oracle

MySQL

ODBC

Non-SQL-data

Directory Services, Mail,

Text, Video, ...

OLEDB

ADO.NET

Page 8: Sesión 05 - ADO.Net

ADO.Net

• Qué es ADO.Net?

– Es parte fundamental de NET Framework.

– Es un modelo de objetos desarrollado por Microsoft.

– Provee servicios de acceso a datos para múltiples fuentes de datos.

• Bases de datos relacionales (RDBMS)

• XML

• Archivos Excel, Access, etc…

– Provee componentes para crear aplicaciones web y distribuidas

sobre diversas fuentes de datos.

– Se accede mediante el namespace System.Data.

– Provee escenarios conectados y desconectados.

– Es la evolución de Microsoft ADO (Activex Data Objects).

– Provee una serie de interfaces y clases abstractas para

implementaciones de terceros. (API Independendiente)

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 9: Sesión 05 - ADO.Net

ADO.Net

• ADO.Net 2.0 es una API Independiente

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Interfaces IDb* (ej: IDbConnection)

clases base abstractas Db* (ej: DbConnection)

Implementa la clase base Db*

Sql OleDb ODBC Oracle3rd

Party 1

3rd

Party 2

Provider-

Independiente

del código de

la aplicación

en esta capa

Provider-

específico en

el código de la

aplicación en

esta capa

Page 10: Sesión 05 - ADO.Net

ADO.Net

• Arquitectura de ADO.NET (2 Componentes fundamentales)

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

– El DataSet

• Son representaciones “en memoria” de los

datos.

• Independiente de la fuente de datos.

• Puede utilizar múltiples fuentes de datos.

• Proporciona un conjunto de objetos

(DataTables, DataRow, etc.)

• Utilizan XML para su persistencia.

• Diseñado para escenarios “desconectados”

– Los NET Framework Data Providers

• Son un conjunto de objetos (Connection,

Command, DataReader, DataAdapter).

• Permiten la conexión a la fuente de datos.

• Permiten obtener, modificar y datos.

• Pueden ejecutar “Stored Procedures” y

enviar/recibir parámetros

Page 11: Sesión 05 - ADO.Net

ADO.Net

• Data Providers

– Cualquier aplicación que utiliza

ADO.Net accede a la fuente de

datos mediante un Provider.

– Están programados en código

manejado, pero pueden haber

excepciones.

– Permiten conectar a la BD, ejecutar

comandos y obtener resultados

– Está disponibles mediante sus

respectivos Namespaces.• System.Data.SqlClient

• System.Data.OracleClient

• System.Data.OleDb

– Cada Provider implementa

interfaces para sus objetos.

– Se pueden implementar Providers

por terceros (MySQL, PostgreSQL,

DB2, etc.)

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 12: Sesión 05 - ADO.Net

ADO.Net

• Data Providers - Implementaciones

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

.NET Framework data provider Description

.NET Framework Data Provider for SQL ServerProvides data access for Microsoft SQL Server version 7.0 or later. Uses

the System.Data.SqlClient namespace.

.NET Framework Data Provider for OLE DBFor data sources exposed using OLE DB. Uses the System.Data.OleDb

namespace.

.NET Framework Data Provider for ODBCFor data sources exposed using ODBC. Uses the System.Data.Odbc

namespace.

.NET Framework Data Provider for Oracle

For Oracle data sources. The .NET Framework Data Provider for Oracle

supports Oracle client software version 8.1.7 and later, and uses the

System.Data.OracleClient namespace.

Page 13: Sesión 05 - ADO.Net

ADO.Net

• Data Providers - Objetos

– Connection (Establece y libera conexiones a la BD)

– Command (Ejecuta comandos como sentencias SQL, Stored Procedures,

actualizaciones sobre la BD, etc.)

– DataReader (Provee acceso directo, secuencial y de sólo lectura a los datos)

– DataAdapter (Permite poblar DataSets y realizar sincronización sobre la BD)

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 14: Sesión 05 - ADO.Net

ADO.Net

• Data Providers – Objetos adicionales

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Object Description

TransactionEnables you to enlist commands in transactions at the data source. The base class for all Transaction objects

is the DbTransaction class.

CommandBuilder

A helper object that will automatically generate command properties of a DataAdapter or will derive

parameter information from a stored procedure and populate the Parameters collection of a Command

object. The base class for all CommandBuilder objects is the DbCommandBuilder class.

ConnectionStringBuilder

A helper object that provides a simple way to create and manage the contents of connection strings used by

the Connection objects. The base class for all ConnectionStringBuilder objects is the

DbConnectionStringBuilder class.

ParameterDefines input, output, and return value parameters for commands and stored procedures. The base class for

all Parameter objects is the DbParameter class.

Exception

Returned when an error is encountered at the data source. For an error encountered at the client, .NET

Framework data providers throw a .NET Framework exception. The base class for all Exception objects is the

DbException class.

Error Exposes the information from a warning or error returned by a data source.

ClientPermissionProvided for .NET Framework data provider code access security attributes. The base class for all

ClientPermission objects is the DBDataPermission class.

Page 15: Sesión 05 - ADO.Net

ADO.Net

• Data Providers – Escogiendo el apropiado

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Provider Notes

.NET Framework Data Provider for SQL Server

Recommended for middle-tier applications using Microsoft SQL Server 7.0 or later.

Recommended for single-tier applications using Microsoft Database Engine (MSDE) or

SQL Server 7.0 or later.

Recommended over use of the OLE DB Provider for SQL Server (SQLOLEDB) with the

.NET Framework Data Provider for OLE DB.

For SQL Server 6.5 and earlier, you must use the OLE DB Provider for SQL Server with

the .NET Framework Data Provider for OLE DB.

.NET Framework Data Provider for OLE DB

Recommended for middle-tier applications using SQL Server 6.5 or earlier.

For SQL Server 7.0 or later, the .NET Framework Data Provider for SQL Server is

recommended.

Also recommended for single-tier applications using Microsoft Access databases. Use of

an Access database for a middle-tier application is not recommended.

.NET Framework Data Provider for ODBC Recommended for middle and single-tier applications using ODBC data sources.

.NET Framework Data Provider for Oracle Recommended for middle and single-tier applications using Oracle data sources.

Page 16: Sesión 05 - ADO.Net

ADO.Net

• Data Providers

– Objeto Connection

• Provee la capacidad de conexión a cualquier fuente

de datos.

• Cada Provider proporciona su implementación:

• La información necesaria para realizar la conexión se

entrega mediante la propiedad ConnectionString.

• Abre la conexión con la BD mediante el método

Open().

• Cierra la conexión con la BD mediante el método

Close().

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 17: Sesión 05 - ADO.Net

ADO.Net

• Data Providers

– Objeto Command

• Una vez establecida la conexión, se utiliza el objeto Command.

• Puede ejecutar consultas de inserción, modificación, eliminación

de datos, etc.

• Puede invocar “Stored Procedures”.

• Maneja el envío y recepción de parámetros.

• Métodos:

– ExecuteReader() : ejecuta una consulta que devuelve un conjunto de datos

(DataReader ) .

– ExecuteScalar(): ejecuta una consulta que devuelve un simple valor escalar.

– ExecuteXmlReader(): ejecuta una consulta que devuelve un conjunto de

datos en formato XML (Sólo para SqlCommand).

– ExecuteNonQuery() : ejecuta una actualización de datos o similar.

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 18: Sesión 05 - ADO.Net

ADO.Net

• Data Providers

– Objeto DataReader

• Proporcionan acceso rápido a la data.

• Sólo se mueven hacia adelante y es read-only.

• Sólo pueden leer una fila a la vez.

• Para leer una fila se utiliza el método Read().

• Para leer los valores de la fila se utilizan los métodos

Get: GetString(n), GetInt32(n), etc.

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 19: Sesión 05 - ADO.Net

ADO.Net

• Data Providers

– Objeto DataAdapter

• Es el puente entre las partes desconectadas y conectadas de ADO.Net

• Utiliza los objetos Command para poblar los objetos desconectados

(DataSet).

• Utiliza los objetos Command para actualizar la BD en base a las

modificaciones del DataSet.

• El método Fill() puede llenar DataSets o DataTables.

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 20: Sesión 05 - ADO.Net

ADO.Net

• El DataAdapter (panorama)

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 21: Sesión 05 - ADO.Net

ADO.Net

• DataSet

– Representación en memoria de datos de

múltiples fuentes.

– Es independiente de la fuente de datos.

– Permite acceso y manejo más flexible de

la data que el DataReader.

– Pueden modificar la data a diferencia de

los DataReaders (read-only).

– Pueden guardar los cambios en la BD,

mediante el DataAdapter.

– Contiene múltiples objetos (DataTable,

DataColumn, DataView, etc.)

– Utilizan XML para su persistencia

– Diseñado para escenarios desconectados.

– Es la base sobre la cual se construyen los

DataSets tipados.

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 22: Sesión 05 - ADO.Net

ADO.Net

• DataSet

– Modelo de objetos

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 23: Sesión 05 - ADO.Net

ADO.Net

• Dataset (esquema)

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

DataSet

.Tables[...]

.Relations[...]

...

DataTable

.Columns[..]

.Rows[..]

DataTable

.Columns[...]

.Rows[...]

.DefaultView

...

DataRow

DataRowdata

DataColumn

schema

DataColumn

DataView

DataRelationDataRelation

Page 24: Sesión 05 - ADO.Net

ADO.Net

• DataSet - DataAdapter

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected]) 24

ADO.NET Content Components

XML file

DataSet

Tables

Relations

DataTable

ReadXml

WriteXml

DataTable

Constraints

DataColumn

DataRow

DataRelation

connection-oriented connectionless

ADO.NET Managed

Providers

Database

Update

Fill

Connectionless data flow Connection-oriented data flow

DataAdapter

Page 25: Sesión 05 - ADO.Net

ADO.Net

• LINQ (Net Framework 3.5)

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

var overdrawnQuery = from account in db.Accounts

where account.Balance < 0

select new { account.Name, account.Address };

Page 26: Sesión 05 - ADO.Net

ADO.Net

• Clases Comunes (Revisión)

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Base de Datos

XxxConnection

XxxCommand

DataSet XxxDataReader

XxxDataAdapter

Maneja la conexión a una base de

datos

Ejecuta comandos contra una base

de datos

Copia local de datos relacionales

Provee acceso a datos

Read-only, Forward-only

Intercambia datos entre un dataset

y una base de datos

Page 27: Sesión 05 - ADO.Net

ADO.Net

Acceso a Datos – Escenario Conectado

• En un escenario conectado, los recursos se

mantienen en el servidor hasta que la conexión

se cierra.

• Pasos:1. Abrir Conexión

2. Ejecutar Comando

3. Procesar Filas en DataReader

4. Cerrar Reader

5. Cerrar Conexión

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 28: Sesión 05 - ADO.Net

ADO.Net

Acceso a Datos – Escenario Desconectado

• En un escenario desconectado, los recursos no se

mantienen en el servidor mientras los datos se

procesan.

• Pasos:

1. Abrir Conexión

2. Llenar DataSet mediante DataAdapter

3. Cerrar Conexión

4. Procesar DataSet

5. Abrir Conexión

6. Actualizar fuente de datos mediante DataAdapter

7. Cerrar Conexión

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 29: Sesión 05 - ADO.Net

ADO.Net

• Ejemplos de ADO.Net

– Objeto Connection

– Objeto Command

• ExecuteReader()

• ExecuteScalar()

• ExecuteXmlReader()

• ExecuteNonQuery()

• Comandos Paramétricos

– Objeto DataReader

– Objeto DataAdapter

– Objeto DataSet - DataAdapterDesarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Page 30: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo del Objeto Connection

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

string connectionString = "Data Source=(local); Initial Catalog=Adventureworks; " +

"Integrated Security=SSPI; Persist Security Info=False";

SqlConnection connection = new SqlConnection(connectionString);

connection.Open();

using (connection)

{

// Use the database connection.

}

SqlConnection Cn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial

Catalog=Adventureworks");

Cn.Open();

// Operaciones de Acceso a Datos

Cn.Close();

string connectionString = ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;

Page 31: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de objeto Connection utilizando

ConnectionStringBuilder

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

using System;

using System.Data.SqlClient;

namespace ConnectionTest

{

class Program

{

static void Main(string[] args)

{

SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();

connBuilder.InitialCatalog = "TestDB";

connBuilder.DataSource = @".\SQLExpress";

connBuilder.IntegratedSecurity = true;

SqlConnection conn = new SqlConnection(connBuilder.ConnectionString);

conn.Open();

Console.WriteLine("Connected to SQL Server v" + conn.ServerVersion);

conn.Close();

Console.ReadLine();

}

}

}

Page 32: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de ExecuteReader() 1/2

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

// Middle-tier class, which contains a business method that returns a data reader.

public class MyProductsDAC

{

public static SqlDataReader GetProductReader()

{

SqlConnection connection = new SqlConnection(aConnectionString);

connection.Open();

string sql = "SELECT Name, ListPrice FROM Production.Product";

SqlDataReader reader;

using (SqlCommand command = new SqlCommand(sql, connection))

{

command.CommandType = CommandType.Text;

reader = command.ExecuteReader(CommandBehavior.SingleResult |

CommandBehavior.CloseConnection);

} // Dispose command object.

return reader;

}

}

Page 33: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de ExecuteReader() 2/2

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

// User-interface component, which calls the middle-tier business method.

public class MyUserInterfaceComponent

{

public void MyMethod()

{

using (SqlDataReader reader = MyProductsDAC.GetProductReader())

{

while (reader.Read())

{

Console.WriteLine("Product name: {0}", reader.GetString(0));

Console.WriteLine("Product price: {0}", reader.GetDecimal(1));

}

} // Dispose data reader, which also closes the connection.

}

}

Page 34: Sesión 05 - ADO.Net

ADO.Net

• Ejemplos de ExecuteScalar()

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

SqlConnection connection = new SqlConnection(aConnectionString);

SqlCommand command = new SqlCommand( "SELECT COUNT(*) FROM Production.Product", connection);

command.CommandType = CommandType.Text;

connection.Open();

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

connection.Close();

using (SqlConnection connection = new SqlConnection(aConnectionString))

{

connection.Open();

using (SqlCommand command = new SqlCommand(

"SELECT AVG(ListPrice) FROM Production.Product",

connection))

{

command.CommandType = CommandType.Text;

decimal count = (decimal) command.ExecuteScalar();

// Use query result.

} // Dispose command object.

} // Dispose (close) connection object.

Page 35: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de ExecuteXmlReader()

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

using (SqlConnection connection = new SqlConnection(aConnectionString))

{

connection.Open();

using ( SqlCommand command = new SqlCommand("SELECT Name, ListPrice FROM

Production.Product FOR XML AUTO“, connection) )

{

command.CommandType = CommandType.Text;

XmlReader reader = command.ExecuteXmlReader();

while (reader.Read())

{

// Process XML node.

}

reader.Close();

} // Dispose command object.

} // Dispose (close) connection object.

Page 36: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de ExecuteNonQuery() 1/2

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

public static void ExecuteNonQueryExample(IDbConnection con)

{

// Create and configure a new command.

IDbCommand com = con.CreateCommand();

com.CommandType = CommandType.Text;

com.CommandText = "UPDATE Employees SET Title = 'Sales Director' WHERE EmployeeId = '5'";

// Execute the command and process the result.

int result = com.ExecuteNonQuery();

// Check the result

if (result == 1)

{

Console.WriteLine("Employee title updated.");

}

else

{

Console.WriteLine("Employee title not updated.");

}

}

Page 37: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de ExecuteNonQuery() 2/2

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

using (SqlConnection connection = new SqlConnection(aConnectionString))

{

connection.Open();

using (SqlCommand command = new SqlCommand("uspUpdatePrice", connection))

{

command.CommandType = CommandType.StoredProcedure;

command.Parameters.Add("@prmProductID", SqlDbType.Int).Value = aProductID;

command.Parameters.Add("@prmAmount", SqlDbType.Money).Value = anAmount;

int rowsAffected = command.ExecuteNonQuery();

if (rowsAffected == 1)

Console.WriteLine("The product has been updated successfully.");

else

Console.WriteLine("The product has not been updated.");

} // Dispose command object.

} // Dispose (close) connection object.

Page 38: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de ExecuteNonQuery() 2/2 – Stored

Procedure.

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

CREATE PROCEDURE dbo.uspUpdatePrice

(

@prmProductID int,

@prmAmount money

)

AS

BEGIN

UPDATE Production.Product SET ListPrice = ListPrice + @prmAmount

WHERE ProductID=@prmProductID

END

Page 39: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de Comandos Paramétricos 1/2

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

string sql = "SELECT Name, ListPrice FROM Production.Product WHERE Name LIKE @NamePart";

using (SqlConnection connection = new SqlConnection(aConnectionString))

{

connection.Open();

using (SqlCommand command = new SqlCommand(sql, connection))

{

command.CommandType = CommandType.Text;

command.Parameters.Add("@NamePart", SqlDbType.NVarChar, 50).Value = aName;

using (SqlDataReader reader = command.ExecuteReader())

{

while (reader.Read())

{

Console.WriteLine("Product name: {0}", reader.GetString(0));

Console.WriteLine("Product price: {0}", reader.GetDecimal(1));

}

} // Dispose data reader.

} // Dispose command object.

} // Dispose (close) connection object.

Page 40: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de Comandos Paramétricos 2/2

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

using (SqlConnection connection = new SqlConnection(aConnectionString))

{

connection.Open();

using (SqlCommand command = new SqlCommand("uspGetProductsAbovePrice“, connection))

{

command.CommandType = CommandType.StoredProcedure;

command.Parameters.Add("@prmPrice", SqlDbType.Money).Value = aPrice;

command.Parameters.Add("@prmAverage", SqlDbType.Money).Direction = ParameterDirection.Output;

command.Parameters.Add("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

using (SqlDataReader reader = command.ExecuteReader())

{

while (reader.Read())

{

Console.WriteLine("Product name: {0}", reader.GetString(0));

Console.WriteLine("Product price: {0}", reader.GetDecimal(1));

}

} // Dispose (close) data reader object.

decimal average = (decimal) command.Parameters["@prmAverage"].Value;

Console.WriteLine("Average price above threshold: {0}", average);

int count = (int) command.Parameters["@RETURN_VALUE"].Value;

Console.WriteLine("Number of products above threshold: {0}", count);

} // Dispose command object.

} // Dispose (close) connection object.

Page 41: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de Comandos Paramétricos 2/2

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

CREATE PROCEDURE dbo.uspGetProductsAbovePrice

(

@prmPrice decimal,

@prmAverage decimal OUTPUT

)

AS

BEGIN

DECLARE @varCount int

SELECT

@prmAverage=AVG(ListPrice), @varCount=COUNT(*)

FROM

Production.Product

WHERE

ListPrice > @prmPrice

SELECT

Name, ListPrice

FROM

Production.Product

WHERE

ListPrice > @prmPrice

RETURN @varCount

END

Page 42: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de DataReader 1/4

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

using System.Data.SqlClient;

class DataReaderExample

{

public static void Main()

{

SqlConnection Cn = new SqlConnection( "Data Source=localhost; Integrated Security=SSPI; Initial

Catalog=example");

SqlCommand Cmd = Cn.CreateCommand();

Cmd.CommandText = "SELECT Name, Age FROM Employees";

Cn.Open();

SqlDataReader Rdr = Cmd.ExecuteReader();

while (Rdr.Read())

{

System.Console.WriteLine( "Name: {0}, Age: {1}“, Rdr.GetString(0), Rdr.GetInt32(1));

}

Rdr.Close();

Cn.Close();

}

}

Page 43: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de DataReader 2/4

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

class Program

{

static void Main(string[] args)

{

SqlConnectionStringBuilder scb = new SqlConnectionStringBuilder();

scb.DataSource = @".\SQLExpress";

scb.InitialCatalog = "TestDB";

scb.IntegratedSecurity = true;

SqlConnection conn = new SqlConnection(scb.ConnectionString);

conn.Open();

SqlCommand cmd = conn.CreateCommand();

cmd.CommandText = "SELECT * From Users";

SqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read())

{

Console.WriteLine(string.Format("User {0}, Full Name {1} {2}", rdr.GetString(rdr.GetOrdinal("UserName")),

(string)rdr["FirstName"], rdr.GetString(rdr.GetOrdinal("LastName"))));

}

rdr.Close();

conn.Close();

Console.ReadLine();

}

}

Page 44: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de DataReader 3/4

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

class Program

{

static void Main()

{

string connectionString = "Data Source=(local);Initial Catalog=Northwind; Integrated

Security=SSPI";

string queryString = "SELECT CategoryID, CategoryName FROM dbo.Categories;";

using (SqlConnection connection = new SqlConnection(connectionString))

{

SqlCommand command = connection.CreateCommand();

command.CommandText = queryString;

try

{

connection.Open();

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())

{

Console.WriteLine("\t{0}\t{1}“, reader[0], reader[1]);

}

reader.Close();

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

}

}

Page 45: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de DataReader 4/4

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

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();

}

}

Page 46: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de DataAdapter/DataSet: Llenado de un DataSet

con una Tabla

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

private void FillUserTable()

{

DataSet myData = new DataSet();

string connectionString = "Data Source=(local);Initial Catalog=Test;Integrated

Security=SSPI;";

using (SqlConnection testConnection = new SqlConnection(connectionString))

{

SqlCommand testCommand = testConnection.CreateCommand();

testCommand.CommandText = "Select * from userTable";

SqlDataAdapter dataAdapter = new SqlDataAdapter(testCommand);

dataAdapter.Fill(myData, "UserTable");

} // testConnection.Dispose called automatically.

}

Page 47: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de DataAdapter/DataSet: Llenado de un DataSet

de 2 Tablas

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

private void buttonFillData_Click(object sender, EventArgs e)

{

string connectionString =

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

DataSet userData = new DataSet();

using (SqlConnection testConnection = new SqlConnection(connectionString))

{

SqlCommand testCommand = testConnection.CreateCommand();

testCommand.CommandText =

"Select FirstName, LastName from userTable;" +

" Select PermissionType from PermissionsTable";

SqlDataAdapter dataAdapter = new SqlDataAdapter(testCommand);

dataAdapter.Fill(userData);

} // testConnection.Dispose called automatically.

}

Page 48: Sesión 05 - ADO.Net

ADO.Net

• Ejemplo de DataAdapter/DataSet: Llenado de un DataSet

de 2 Tablas mediante un Stored Procedure

Desarrollo de aplicaciones .NET

Eduardo Rivera Alva - MCTS.Net ([email protected])

Create Procedure GetMultipleResults

As

Begin

Select FirstName, LastName from userTable;

Select PermissionType from PermissionsTable;

End

Page 49: Sesión 05 - ADO.Net

Que veremos la próxima sesión?

• Windows Forms y Aplicaciones

Desarrollo de aplicaciones .NETEduardo Rivera Alva - MCTS.Net ([email protected])

Page 50: Sesión 05 - ADO.Net

Desarrollo de aplicaciones .NETEduardo Rivera Alva - MCTS.Net ([email protected])

Fin de la sesión

• Dudas, comentarios, sugerencias?

• Comunicarse por email a [email protected]

• Gracias por su atención !!