Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Ado.net

660 views

Published on

manual deado.net

Published in: Internet
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • -- DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT -- ......................................................................................................................... ......................................................................................................................... Download FULL PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... (Unlimited)
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

Ado.net

  1. 1. Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) Desarrollo de Aplicaciones Capítulo 05 ADO.Net
  2. 2. Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) 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?
  3. 3. Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) Repaso sesión anterior •Arrays –Uni-dimensionales, Multidimensionales –Estructura interna –Arraystipo valor y tipo referencia –Iteración •Colecciones –ArrayList •Ver diapositivas previas.
  4. 4. ADO.Net Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) Referencias 1.Understanding .NET. Caps. 6 (AccesingData: ADO.Net) 2.NET Framework Developer’s Guide: ADO.NET (http://msdn2.microsoft.com/en- us/library/e80y5yhx(VS.80).aspx) 3.ApressPro ADO.NET.2.0.
  5. 5. 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 .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  6. 6. ADO.Net •Qué propone NET Framework? Desarrollo de aplicaciones .NET Eduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  7. 7. ADO.Net •ADO.NET Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) SQL-dataMS SQL Server, Oracle, Jet, Foxpro, ... SQL ServerOracleMySQL ODBCNon-SQL-dataDirectory Services, Mail, Text, Video, ... OLEDBADO.NET
  8. 8. 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 namespaceSystem.Data. –Provee escenarios conectados y desconectados. –Es la evolución de Microsoft ADO (ActivexData Objects). –Provee una serie de interfaces y clases abstractas para implementaciones de terceros. (API Independendiente) Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  9. 9. ADO.Net •ADO.Net2.0 es una API Independiente Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) Interfaces IDb* (ej: IDbConnection) clasesbase abstractasDb* (ej: DbConnection) Implementa la clase baseDb* Sql OleDbODBCOracle3rdParty 13rdParty 2Provider- 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
  10. 10. ADO.Net •Arquitectura de ADO.NET (2 Componentes fundamentales) Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) –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 “StoredProcedures” y enviar/recibir parámetros
  11. 11. ADO.Net •Data Providers –Cualquier aplicación que utiliza ADO.Netaccede 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 Providerimplementa interfaces para sus objetos. –Se pueden implementar Providerspor terceros (MySQL, PostgreSQL, DB2, etc.) Desarrollo de aplicaciones .NETEduardo Rivera Alva-MCTS.Net(eriveraa@gmail.com)
  12. 12. ADO.Net •Data Providers-Implementaciones Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) .NET Framework data provider Description .NET Framework Data Provider for SQL Server Provides data access for Microsoft SQL Server version 7.0 or later. Uses the System.Data.SqlClientnamespace. .NET Framework Data Provider for OLE DB For data sources exposed using OLE DB. Uses the System.Data.OleDbnamespace. .NET Framework Data Provider for ODBC For data sources exposed using ODBC. Uses the System.Data.Odbcnamespace. .NET Framework Data ProviderforOracle ForOracle data sources. The.NET Framework Data ProviderforOracle supportsOracle clientsoftware version8.1.7 and later, and uses theSystem.Data.OracleClientnamespace.
  13. 13. ADO.Net •Data Providers-Objetos –Connection(Establece y libera conexiones a la BD) –Command(Ejecuta comandos como sentencias SQL, StoredProcedures, actualizaciones sobre la BD, etc.) –DataReader(Provee acceso directo, secuencial y de sólo lectura a los datos) –DataAdapter(Permite poblar DataSetsy realizar sincronización sobre la BD) Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  14. 14. ADO.Net •Data Providers–Objetos adicionales Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) Object Description Transaction Enables you to enlist commands in transactions at the data source. The base class for all Transactionobjects is the DbTransactionclass. CommandBuilder A helper object that will automatically generate command properties of a DataAdapteror will derive parameter information from a stored procedure and populate the Parameterscollection of a Commandobject. The base class for all CommandBuilderobjects is the DbCommandBuilderclass. ConnectionStringBuilder A helper object that provides a simple way to create and manage the contents of connection strings used by the Connectionobjects. The base class for all ConnectionStringBuilderobjects is the DbConnectionStringBuilderclass. Parameter Defines input, output, and return value parameters for commands and stored procedures. The base class for all Parameterobjects is the DbParameterclass. 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 Exceptionobjects is the DbExceptionclass. Error Exposes the information from a warning or error returned by a data source. ClientPermission Provided for .NET Framework data provider code access security attributes. The base class for all ClientPermissionobjects is the DBDataPermissionclass.
  15. 15. ADO.Net •Data Providers–Escogiendo el apropiado Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) Provider Notes .NET Framework Data Provider for SQL Server Recommendedformiddle-tierapplicationsusingMicrosoft SQL Server 7.0 orlater. Recommendedforsingle-tierapplicationsusingMicrosoft DatabaseEngine(MSDE) orSQL Server 7.0 orlater. Recommendedoveruse of theOLE DB ProviderforSQL Server (SQLOLEDB) withthe.NET Framework Data ProviderforOLE DB. ForSQL Server 6.5 and earlier, youmustuse theOLE DB ProviderforSQL Server withthe.NET Framework Data ProviderforOLE 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 ProviderforOracle Recommended for middle and single-tier applications using Oracle data sources.
  16. 16. ADO.Net •Data Providers –Objeto Connection •Provee la capacidad de conexión a cualquier fuente de datos. •Cada Providerproporciona 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 .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  17. 17. 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 “StoredProcedures”. •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 .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  18. 18. 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 .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  19. 19. ADO.Net •Data Providers –Objeto DataAdapter •Es el puente entre las partes desconectadas y conectadas de ADO.Net •Utiliza los objetos Commandpara poblar los objetos desconectados (DataSet). •Utiliza los objetos Commandpara actualizar la BD en base a las modificaciones del DataSet. •El método Fill() puede llenar DataSetso DataTables. Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  20. 20. ADO.Net •El DataAdapter(panorama) Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  21. 21. 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 DataSetstipados. Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  22. 22. ADO.Net •DataSet –Modelo de objetos Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  23. 23. ADO.Net •Dataset(esquema) Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) DataSet .Tables[...] .Relations[...] ... DataTable .Columns[..] .Rows[..] DataTable .Columns[...] .Rows[...] .DefaultView... DataRowDataRowdataDataColumnschemaDataColumn DataViewDataRelationDataRelation
  24. 24. ADO.Net • DataSet - DataAdapter Desarrollo de aplicaciones .NET Eduardo Rivera Alva - MCTS.Net (eriveraa@gmail.com) 24 ADO.NET Content Components XML fil e Dat aSet Tabl es Rel ati ons Dat aTabl e ReadXml Writ eXml Dat aTabl e Constr ai nt s Dat aCol umn Dat aRow Dat aRel ati on connectionless connection-oriented ADO.NET Managed Providers Database Update Fill Connectionless data flow Connection-oriented data flow DataAdapter
  25. 25. ADO.Net •LINQ (Net Framework 3.5) Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) varoverdrawnQuery= from account in db.Accountswhere account.Balance< 0select new { account.Name, account.Address};
  26. 26. ADO.Net •ClasesComunes(Revisión) Desarrollo de aplicaciones .NET Eduardo Rivera Alva-MCTS.Net(eriveraa@gmail.com) Base de Datos XxxConnection XxxCommand DataSet XxxDataReader XxxDataAdapter Manejala conexióna unabase de datos Ejecuta comandos contra una base de datos Copialocal de datosrelacionales Proveeaccesoa datos Read-only, Forward-only Intercambiadatosentreun dataset y unabase de datos
  27. 27. ADO.Net Accesoa Datos–EscenarioConectado •En un escenarioconectado, losrecursosse mantienenen el servidorhastaquela conexiónse cierra. •Pasos: 1.AbrirConexión 2.EjecutarComando 3.ProcesarFilasen DataReader 4.CerrarReader 5.CerrarConexión Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  28. 28. ADO.Net Accesoa Datos–EscenarioDesconectado •En un escenariodesconectado, losrecursosno se mantienenen el servidormientraslosdatosse procesan. •Pasos: 1.AbrirConexión 2.LlenarDataSetmedianteDataAdapter 3.CerrarConexión 4.ProcesarDataSet 5.AbrirConexión 6.Actualizarfuentede datosmedianteDataAdapter 7.CerrarConexión Desarrollo de aplicaciones .NET Eduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  29. 29. ADO.Net •Ejemplos de ADO.Net –Objeto Connection –Objeto Command •ExecuteReader() •ExecuteScalar() •ExecuteXmlReader() •ExecuteNonQuery() •Comandos Paramétricos –Objeto DataReader –Objeto DataAdapter –Objeto DataSet-DataAdapter Desarrollo de aplicaciones .NET Eduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com)
  30. 30. ADO.Net •Ejemplo del Objeto Connection Desarrollo de aplicaciones .NET Eduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) string connectionString= "Data Source=(local); Initial Catalog=Adventureworks; " + "Integrated Security=SSPI; Persist Security Info=False"; SqlConnectionconnection = new SqlConnection(connectionString); connection.Open(); using (connection) { // Use the database connection. } SqlConnectionCn= new SqlConnection("Data Source=localhost;IntegratedSecurity=SSPI;InitialCatalog=Adventureworks"); Cn.Open(); // Operaciones de Acceso a Datos Cn.Close(); stringconnectionString= ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;
  31. 31. ADO.Net •Ejemplo de objeto Connectionutilizando ConnectionStringBuilder Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) usingSystem; usingSystem.Data.SqlClient; namespaceConnectionTest { classProgram { staticvoidMain(string[] args) { SqlConnectionStringBuilderconnBuilder= new SqlConnectionStringBuilder(); connBuilder.InitialCatalog= "TestDB"; connBuilder.DataSource= @".SQLExpress"; connBuilder.IntegratedSecurity= true; SqlConnectionconn= new SqlConnection(connBuilder.ConnectionString); conn.Open(); Console.WriteLine("Connected to SQL Server v" + conn.ServerVersion); conn.Close(); Console.ReadLine(); } } }
  32. 32. ADO.Net •Ejemplo de ExecuteReader() 1/2 Desarrollo de aplicaciones .NET Eduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) // Middle-tierclass, whichcontainsa businessmethodthatreturnsa data reader. publicclassMyProductsDAC{ publicstaticSqlDataReaderGetProductReader() { SqlConnectionconnection= new SqlConnection(aConnectionString); connection.Open(); stringsql= "SELECT Name, ListPriceFROM Production.Product"; SqlDataReaderreader; using(SqlCommandcommand= new SqlCommand(sql, connection)) { command.CommandType= CommandType.Text; reader= command.ExecuteReader(CommandBehavior.SingleResult| CommandBehavior.CloseConnection); } // Disposecommandobject. returnreader; } }
  33. 33. ADO.Net •Ejemplo de ExecuteReader() 2/2 Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) // User-interface component, whichcallsthemiddle-tierbusinessmethod. publicclassMyUserInterfaceComponent{ publicvoidMyMethod() { using(SqlDataReaderreader= MyProductsDAC.GetProductReader()) { while(reader.Read()) { Console.WriteLine("Productname: {0}", reader.GetString(0)); Console.WriteLine("Productprice: {0}", reader.GetDecimal(1)); } } // Disposedata reader, whichalsoclosestheconnection. } }
  34. 34. ADO.Net •Ejemplos de ExecuteScalar() Desarrollo de aplicaciones .NET Eduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) SqlConnectionconnection= new SqlConnection(aConnectionString); SqlCommandcommand= new SqlCommand( "SELECT COUNT(*) FROM Production.Product", connection); command.CommandType= CommandType.Text; connection.Open(); intcount= (int)command.ExecuteScalar(); connection.Close(); using(SqlConnectionconnection= new SqlConnection(aConnectionString)) { connection.Open(); using(SqlCommandcommand= new SqlCommand( "SELECT AVG(ListPrice) FROM Production.Product", connection)) { command.CommandType= CommandType.Text; decimal count= (decimal) command.ExecuteScalar(); // Use queryresult. } // Disposecommandobject. } // Dispose(close) connectionobject.
  35. 35. ADO.Net •Ejemplo de ExecuteXmlReader() Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) using(SqlConnectionconnection= new SqlConnection(aConnectionString)) { connection.Open(); using( SqlCommandcommand= new SqlCommand("SELECT Name, ListPriceFROM Production.ProductFOR XML AUTO“,connection) ) { command.CommandType= CommandType.Text; XmlReaderreader= command.ExecuteXmlReader(); while(reader.Read()) { // ProcessXML node. } reader.Close(); } // Disposecommandobject. } // Dispose(close) connectionobject.
  36. 36. ADO.Net •Ejemplo de ExecuteNonQuery() 1/2 Desarrollo de aplicaciones .NET Eduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) public static void ExecuteNonQueryExample(IDbConnectioncon) { // Create and configure a new command. IDbCommandcom= con.CreateCommand(); com.CommandType= CommandType.Text; com.CommandText= "UPDATE Employees SET Title = 'Sales Director' WHERE EmployeeId= '5'"; // Execute the command and process the result. intresult= com.ExecuteNonQuery(); // Checktheresultif(result== 1) { Console.WriteLine("Employeetitleupdated."); } else{ Console.WriteLine("Employee title not updated."); } }
  37. 37. ADO.Net •Ejemplo de ExecuteNonQuery() 2/2 Desarrollo de aplicaciones .NET Eduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) using(SqlConnectionconnection= new SqlConnection(aConnectionString)) { connection.Open(); using(SqlCommandcommand= new SqlCommand("uspUpdatePrice", connection)) { command.CommandType= CommandType.StoredProcedure; command.Parameters.Add("@prmProductID", SqlDbType.Int).Value= aProductID; command.Parameters.Add("@prmAmount", SqlDbType.Money).Value= anAmount; introwsAffected= command.ExecuteNonQuery(); if(rowsAffected== 1) Console.WriteLine("Theproducthas beenupdatedsuccessfully."); elseConsole.WriteLine("Theproducthas notbeenupdated."); } // Disposecommandobject. } // Dispose(close) connectionobject.
  38. 38. ADO.Net •Ejemplo de ExecuteNonQuery() 2/2 –StoredProcedure. Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) CREATE PROCEDURE dbo.uspUpdatePrice( @prmProductIDint, @prmAmountmoney) ASBEGINUPDATE Production.ProductSET ListPrice= ListPrice+ @prmAmountWHERE ProductID=@prmProductIDEND
  39. 39. ADO.Net •Ejemplo de Comandos Paramétricos1/2 Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) stringsql= "SELECT Name, ListPriceFROM Production.ProductWHERE NameLIKE @NamePart"; using(SqlConnectionconnection= new SqlConnection(aConnectionString)) { connection.Open(); using(SqlCommandcommand= new SqlCommand(sql, connection)) { command.CommandType= CommandType.Text; command.Parameters.Add("@NamePart", SqlDbType.NVarChar, 50).Value= aName; using(SqlDataReaderreader= command.ExecuteReader()) { while(reader.Read()) { Console.WriteLine("Productname: {0}", reader.GetString(0)); Console.WriteLine("Productprice: {0}", reader.GetDecimal(1)); } } // Disposedata reader. } // Disposecommandobject. } // Dispose(close) connectionobject.
  40. 40. ADO.Net •Ejemplo de Comandos Paramétricos2/2 Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) using(SqlConnectionconnection= new SqlConnection(aConnectionString)) { connection.Open(); using(SqlCommandcommand= 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(SqlDataReaderreader= command.ExecuteReader()) { while(reader.Read()) { Console.WriteLine("Productname: {0}", reader.GetString(0)); Console.WriteLine("Productprice: {0}", reader.GetDecimal(1)); } } // Dispose(close) data readerobject. decimal average= (decimal) command.Parameters["@prmAverage"].Value; Console.WriteLine("Averagepriceabovethreshold: {0}", average); intcount= (int) command.Parameters["@RETURN_VALUE"].Value; Console.WriteLine("Numberof productsabovethreshold: {0}", count); } // Disposecommandobject. } // Dispose(close) connectionobject.
  41. 41. ADO.Net •Ejemplo de Comandos Paramétricos2/2 Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) CREATE PROCEDURE dbo.uspGetProductsAbovePrice( @prmPricedecimal, @prmAveragedecimal OUTPUT) ASBEGINDECLARE @varCountintSELECT@prmAverage=AVG(ListPrice), @varCount=COUNT(*) FROMProduction.ProductWHEREListPrice> @prmPriceSELECTName, ListPriceFROMProduction.ProductWHEREListPrice> @prmPriceRETURN @varCountEND
  42. 42. ADO.Net •Ejemplo de DataReader1/4 Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) usingSystem.Data.SqlClient; classDataReaderExample{ publicstaticvoidMain() { SqlConnectionCn= new SqlConnection( "Data Source=localhost; IntegratedSecurity=SSPI; InitialCatalog=example"); SqlCommandCmd= Cn.CreateCommand(); Cmd.CommandText= "SELECT Name, AgeFROM Employees"; Cn.Open(); SqlDataReaderRdr= Cmd.ExecuteReader(); while(Rdr.Read()) { System.Console.WriteLine( "Name: {0}, Age: {1}“, Rdr.GetString(0), Rdr.GetInt32(1)); } Rdr.Close(); Cn.Close(); } }
  43. 43. ADO.Net •Ejemplo de DataReader2/4 Desarrollo de aplicaciones .NET Eduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) classProgram{ staticvoidMain(string[] args) { SqlConnectionStringBuilderscb= new SqlConnectionStringBuilder(); scb.DataSource= @".SQLExpress"; scb.InitialCatalog= "TestDB"; scb.IntegratedSecurity= true; SqlConnectionconn= new SqlConnection(scb.ConnectionString); conn.Open(); SqlCommandcmd= conn.CreateCommand(); cmd.CommandText= "SELECT * FromUsers"; SqlDataReaderrdr= 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(); } }
  44. 44. ADO.Net •Ejemplo de DataReader3/4 Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) classProgram{ staticvoidMain() { stringconnectionString= "Data Source=(local);InitialCatalog=Northwind; IntegratedSecurity=SSPI"; stringqueryString= "SELECT CategoryID, CategoryNameFROM dbo.Categories;"; using(SqlConnectionconnection= new SqlConnection(connectionString)) { SqlCommandcommand= connection.CreateCommand(); command.CommandText= queryString; try{ connection.Open(); SqlDataReaderreader= command.ExecuteReader(); while(reader.Read()) { Console.WriteLine("t{0}t{1}“, reader[0], reader[1]); } reader.Close(); } catch (Exceptionex) { Console.WriteLine(ex.Message); } } } }
  45. 45. ADO.Net •Ejemplo de DataReader4/4 Desarrollo de aplicaciones .NET Eduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) staticvoidHasRows(SqlConnectionconnection) { using(connection) { SqlCommandcommand= new SqlCommand("SELECT CategoryID, CategoryNameFROM Categories;“, connection); connection.Open(); SqlDataReaderreader= command.ExecuteReader(); if(reader.HasRows) { while(reader.Read()) { Console.WriteLine("{0}t{1}", reader.GetInt32(0), reader.GetString(1)); } } else{ Console.WriteLine("No rowsfound."); } reader.Close(); } }
  46. 46. ADO.Net •Ejemplo de DataAdapter/DataSet: Llenado de un DataSetcon una Tabla Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) privatevoidFillUserTable() { DataSetmyData= new DataSet(); string connectionString= "Data Source=(local);Initial Catalog=Test;IntegratedSecurity=SSPI;"; using (SqlConnectiontestConnection= new SqlConnection(connectionString)) { SqlCommandtestCommand= testConnection.CreateCommand(); testCommand.CommandText= "Select* fromuserTable"; SqlDataAdapterdataAdapter= new SqlDataAdapter(testCommand); dataAdapter.Fill(myData, "UserTable"); } // testConnection.Disposecalledautomatically. }
  47. 47. ADO.Net •Ejemplo de DataAdapter/DataSet: Llenado de un DataSetde 2 Tablas Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) privatevoidbuttonFillData_Click(objectsender, EventArgse) { stringconnectionString= "Data Source=(local);Initial Catalog=Test;IntegratedSecurity=SSPI;"; DataSetuserData= new DataSet(); using (SqlConnectiontestConnection= new SqlConnection(connectionString)) { SqlCommandtestCommand= testConnection.CreateCommand(); testCommand.CommandText= "Select FirstName, LastNamefrom userTable;" + " SelectPermissionTypefromPermissionsTable"; SqlDataAdapterdataAdapter= new SqlDataAdapter(testCommand); dataAdapter.Fill(userData); } // testConnection.Disposecalledautomatically. }
  48. 48. ADO.Net •Ejemplo de DataAdapter/DataSet: Llenado de un DataSetde 2 Tablas mediante un StoredProcedure Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) Create Procedure GetMultipleResultsAsBeginSelect FirstName, LastNamefrom userTable; Select PermissionTypefrom PermissionsTable; End
  49. 49. Que veremos la próxima sesión? •Windows Formsy Aplicaciones Desarrollo de aplicaciones .NETEduardo Rivera Alva-MCTS.Net(eriveraa@gmail.com)
  50. 50. Desarrollo de aplicaciones .NETEduardo Rivera Alva -MCTS.Net (eriveraa@gmail.com) Fin de la sesión •Dudas, comentarios, sugerencias? •Comunicarse por email a eriveraa@gmail.com •Gracias por su atención !!

×