Maurizio Fermeglia mauf@dicamp.univ.trieste.it ACCESSO AI DATI Maurizio Fermeglia mauf@dicamp.univ.trieste.it.

Slides:



Advertisements
Presentazioni simili
Training On Line - CONP. 2 Richiesta Da Menu: Conferimenti ad inizio anno termico > Agosto > Pluriennali > Nuova Richiesta Si accede alla pagina di Richiesta.
Advertisements

© 2010 Colt Telecom Group Limited. All rights reserved. Cloud Computing Lapproccio Colt Dionigi Faccedna.
Dipartimento di Ingegneria Idraulica e Ambientale - Universita di Pavia 1 Caduta non guidata di un corpo rettangolare in un serbatoio Velocità e rotazione.
1 MeDeC - Centro Demoscopico Metropolitano Provincia di Bologna - per Valutazione su alcuni servizi erogati nel.
TAV.1 Foto n.1 Foto n.2 SCALINATA DI ACCESSO ALL’EREMO DI SANTA CATERINA DEL SASSO DALLA CORTE DELLE CASCINE DEL QUIQUIO Foto n.3 Foto n.4.
Elaborazione di Franco Grivet Chin
1 Pregnana Milanese Assessorato alle Risorse Economiche Bilancio Preventivo P R O P O S T A.
Interfacce Java.
Midrange Modernization Conference 1 Scenari evolutivi per le soluzioni basate su AS/400 Walter Poloni Direttore Developer & Platform Evangelism Microsoft.
Luca Bianchi Windows Development Day Bologna 28 gennaio 2005 SQL Server Desktop Engine (MSDE) & SQL Server 2005 Express.
Sql Server 2005 Reporting Services - Sviluppo Franco Perduca Factory Software
ASP.NET – Data Binding Davide Vernole .NET MVP.
ASP.NET – Web Forms Davide Vernole.NET MVP. Di cosa parleremo Introduzione ad ASP.NET ASP.NET, dietro le quinte Componenti principali di una applicazione.
JPA Overview della tecnologia. Java Persistence Architecture Definita nella JSR-220 EJB 3.0 ( Tentativo di unificare EJB2.1 con.
Frontespizio Economia Monetaria Anno Accademico
Un DataBase Management System (DBMS) relazionale client/server.
Microsoft Robotics Studio Marco Petrucco Microsoft Student Partner - Udine.
EJB Enterprise Java Beans B. Pernici. Approccio Java.
Unified Modeling Language class C {…} class B extends C {…} Esiste una notazione grafica per mostrare le relazioni di ereditarietà. Object StringC B Tutte.
HDM Information Design notation v.4. HDM Information Design.
Directory services Directory offline –Elenchi telefonici –Guide TV –Cataloghi acquisti Directory online –Application specific (lotus notes, MS Exchange.
Programmazione 1 9CFU – TANTE ore
Costruzione di Interfacce Lezione 10 Dal Java al C++ parte 1
Ufficio Studi UNIONCAMERE TOSCANA 1 Presentazione di Riccardo Perugi Ufficio Studi UNIONCAMERE TOSCANA Firenze, 19 dicembre 2000.
1. Conoscere luso delle collezioni in Java Comprendere le principali caratteristiche nelle varie classi di Collection disponibili Saper individuare quali.
2000 Prentice Hall, Inc. All rights reserved. 1 Capitolo 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions 3.4Functions.
La partita è molto combattuta perché le due squadre tentano di vincere fino all'ultimo minuto. Era l'ultima giornata del campionato e il risultato era.
MP/RU 1 Dicembre 2011 ALLEGATO TECNICO Evoluzioni organizzative: organico a tendere - ricollocazioni - Orari TSC.
2000 Prentice Hall, Inc. All rights reserved. 1 Capitolo 6: Classi e astrazione dati 1.Introduzione 2.Definizione delle strutture 3.Accedere ai membri.
Cos’è un problema?.
FONDAMENTI DI INFORMATICA III WfMC-1. FONDAMENTI DI INFORMATICA III WfMC-2 WFMC Cose WfMC Workflow Management Coalition (WfMC), Brussels, è unorganizzazione.
Gestione File System e I/O in Windows 2000 Implementazione del File System FAT-12, FAT-16, FAT-32 NTFS API relative al File System Gestione dei dispositivi.
STILI DI APPRENDIMENTO ED EVOLUZIONE INTERFACCE
Sequence. CREARE UNA SEQUENCE CREATE SEQUENCE nome [INCREMENT BY n] [START WITH n] [MAXVALUE n | NOMAXVALUE] [MINVALUE n | NOMINVALUE] [CYCLE | NOCYCLE]
PRODOTTO CARTESIANO Otteniamo un prodotto cartesiano quando: viene omessa la condizione di join una condizione di join non è valida tutte le righe della.
FUNZIONI DI GRUPPO Le funzioni di gruppo operano su un set di record restituendo un risultato per il gruppo. AVG ([DISTINCT|ALL] n) media, ignora i valori.
Constraints.
Componenti dell’architettura Oracle
OO _60-59_ OI_53-54 _ OL _ OR_52-47_ OO= Orientamento allOBIETTIVO OI= Orientamento all'INNOVAZIONE OL= Orientamento alla LEADERSHIPOR= Orientamento.
SQL Server 2012 LocalDB.
Palermo, may 2010 F.Doumaz, S.Vinci (INGV-CNT- Gruppo di telerilevamento)
Q UESTIONI ETICHE E BIOETICHE DELLA DIFESA DELLA VITA NELL AGIRE SANITARIO 1 Casa di Cura Villa San Giuseppe Ascoli Piceno 12 e 13 dicembre 2011.
Q UESTIONI ETICHE E BIOETICHE DELLA DIFESA DELLA VITA NELL AGIRE SANITARIO 1 Casa di Cura Villa San Giuseppe Ascoli Piceno 12 e 13 dicembre 2011.
1 Negozi Nuove idee realizzate per. 2 Negozi 3 4.
ISOIVA (LOCALE) TO ISOIVA (WEB) RIPARTIZIONE INFORMATICA UFFICIO APPLICATIVI AMMINISTRATIVI 13/04/2011 UNIVERSITÀ DEGLI STUDI DI FERRARA 1.
ORDINE DI CHIAMATA a 1minuto e 2 minuti PRINCIPALI TEMPI DELLA COMPETIZIONE ORDINE DI CHIAMATA a 1minuto e 2 minuti PRINCIPALI TEMPI DELLA COMPETIZIONE.
WPF per il client Desktop
Attribution-NonCommercial-ShareAlike Le novità
Scoprirete che su Office non si può solo contare ma anche sviluppare.
24 aprile 2002 Avvisi: Risultati 1 o Esonero: (entro) lunedi 27 disponibili nella pag. WEB, ma anche esposti nella bacheca fuori dal corridoio 2 o dente,
Un trucchetto di Moltiplicazione per il calcolo mentale
21 marzo 2002 (ri-)Avvisi: Giovedi 28 marzo la lezione e sospesa. Nuovo indirizzo di Spedire messaggi e esercizi solo.
VB.NET Sviluppo Applicazioni Desktop
Visual Studio Tools for Office: Developer Solutions Platform Fulvio Giaccari MCSD.NET / MCT Responsabile Usergroup ShareOffice Blog:
SQL Server 2005 Sicurezza Davide Mauri Factory Software
Project Review Novembrer 17th, Project Review Agenda: Project goals User stories – use cases – scenarios Project plan summary Status as of November.
SUBQUERY Chi ha un salario maggiore di quello di Abel? Occorre scomporre la query in due sotto problemi: MAIN : quali impiegati hanno un salario maggiore.
Esempi risolti mediante immagini (e con excel)
Collection & Generics in Java
NO WASTE Progetto continuità scuola primaria scuola secondaria Salorno a.s. 2013_
Sistemi di elaborazione dell’informazione Modulo 3 -Protocolli applicativi Unità didattica 4 - Protocolli del Web Ernesto Damiani Lezione 3 – Esempi HTTP.
SQL Developer Lanciare sqldeveloper (alias sul desktop) / c:\Oracle\sqldeveloper Associare tutti i tipi di file, se volete Tasto destro sulla spina “connection”
Dynamic SQL.
JDBC Java DataBase Connectivity SISTEMI ITIS B. CASTELLI Anno Scolastico
1 Acceleratori e Reattori Nucleari Saverio Altieri Dipartimento di Fisica Università degli Studi - Pavia
Pagine ASP parte 3 I data base Stefano Schacherl.
IL GIOCO DEL PORTIERE CASISTICA. Caso n. 1 Il portiere nella seguente azione NON commette infrazioni.
Esercizio ODBC. Configurare il driver ODBC Start  Control Panel  Administrative Tools Aprire: Data Source(ODBC) User DSN  Add…. Selezionare il driver.
Studente : Andrea Cassarà Classe: 5AII A.S. 2014/2015 Link Sito
ADO Per gestire i database con tecnologia ASP si utilizzano strumenti ADO (ActiveX Data Objects): un'architettura che fornisce oggetti.
Transcript della presentazione:

Maurizio Fermeglia mauf@dicamp.univ.trieste.it ACCESSO AI DATI Maurizio Fermeglia mauf@dicamp.univ.trieste.it

Breve storia dell’Accesso ai Dati VB Objects – API proprietarie Data Access Objects (DAO/Jet) Open Database Connectivity (ODBC) OLE for Databases (OLE/DB) ActiveX Data Objects (ADO) .NET ADO.NET

Il concetto di Accesso ai dati Data Providers Data Consumers Project Mail Proprietary MAPI File System Proprietary Excel Proprietary Tools & Languages Notes Notes API The issue with data access today from the solution devleoper’s point of view is that heterogeneous system integration is difficult or at times impossible due to all the different interfaces used to get to these systems. The learning curve to develop integrated systems, and difficulty maintaining them limits their development. IMS Proprietary Navigational ODBC SQL Svr OCI Oracle Open Lib Sybase

Acesso ai dati con ODBC Data Providers Data Consumers Project Mail Proprietary MAPI File System Proprietary Excel SQL Engine Tools & Languages Notes SQL Engine ODBC ODBC has gone a long way towards solving many of these problems. ODBC provides a single api to a wide variety of data sources today. ODBC is a natural, high speed technology for access to relational systms. ODBC also provides access to non-relational systems, although the interface to these is not a natural. Non-relational systems must be made to look relational by putting a SQL engine in front of the actual data stores and then communication with the data store is SQL. This slows transaction speeds and limits the navigational ability found in these stores. Then there are data stores that simply do not have a SQL interface so access through ODBC is not supported. ODBC will continue to be a valuable technology since it does provide an efficient, high speed access to relational data. One of the key goals for OLE DB is to provide that quality of interface to non-relational stores as well as relational. In doing this, OLE DB will leverage ODBC. From the point of view of the Microsoft solution developer, the programming model is a bit confusing. Sometimes they program directly to ODBC, sometimes to DAO, and sometimes to RDO. SQL Engine IMS SQL Svr DAO RDO Oracle Sybase

Accesso ai Dati con OLE DB Data Providers Data Consumers OLE DB Project OLE DB Mail OLE DB File System OLE DB Excel Tools OLE DB OLE DB Notes DAO Please note that ODBC is not shown here for simplicity’s sake, ODBC drivers are still in the overall equation. It’s important to note that solution developers will rarely or never see OLE DB. OLE DB - along with ODBC - is an ISV technology. It is plumbing at a lower level than is appropriate for a productive solution development environment. Microsoft’s goal is for Data Access Objects (DAO) to be the only data management language used with Microsoft products. RDO will become a subset of DAO. OLE DB simply provides the infrastructure for seamless communication between all data providers. . Languages OLE DB IMS ADO OLE DB SQL Svr OLE DB Oracle OLE DB Sybase

Lo scenario …. Applicatione DAO ADO ADO .NET ODBCDirect RDO JET ODBC Mgr OLEDB ODBC Drv OLEdb-ODBC mdb ISAM SQL Altri…

Access: Accesso a dati via ODBC Microsoft Access DAO 3.5 Jet Database Engine ODBCDirect RDO 2.0 ODBC Driver Manager SQL Server ODBC Driver Other ODBC Driver .MDB Database ISAM Files SQL Server Data Source Other Relational Data Source

La situazione ODBC da un client VB-VC VBSQL ODBC API DAO/JET DAO/ODBCDirect RDO 2.0 SQLDMO Oppure: ADO ADO .Net App VBSQL DAO RDO SQLDMO data ODBC Jet ADO OLEdb

VBSQL Microsoft SQL Server via DB-Library interfaccia alle API del server una delle prime soluzioni per il client/server da applicazioni VB specifica per SQL-Server veloce e lightweight senza interfaccia ad oggetti problemi di conversione da 16 bit (VBX) a 32 bit (OCX)

ODBC API qualsiasi fonte ODBC interfaccia a ODBC Driver Manager difficile da utilizzare, proponibile in un numero molto ridotto di casi specifici sconsigliabile per l’accesso a ISAM richiede l’inclusione delle dichiarazioni delle funzioni molto codice da implementare nell’applicazione cliente

DAO/JET database nativi, ISAM particolari, qualsiasi fonte ODBC paradigma ad oggetti per utilizzare il Jet Engine sui database nativi consente: DDL (TableDefs, QueryDefs, Relations) DML (Recordsets) sicurezza (Users, Groups) replica (metodi e proprietà) usato da Access per i propri documenti e oggetti limiti: stored procedure, eventi, cursori server-side

DAO: Jet Workspace Object Model

DAO/ODBCDirect qualsiasi fonte ODBC salta il Jet Engine nelle connessioni a ODBC richiede RDO non possiede eventi problemi di distribuzione (licenze) consente solo operazioni di DML nato e consigliato per accesso ai dati da Office

ODBCDirect Consente a DAO di accedere a fonti ODBC tramite RDO invece che tramite Jet Per usare ODBCDirect, creare un Workspace di tipo ODBCDirect Set ws = DBEngine.CreateWorkspace(…, dbUseODBC) DBEngine.DefaultType = dbUseODBC Data1.DefaultType = dbUseODBC Porting “rapido” delle applicazioni DAO a ODBCDirect meno overhead in risorse e in prestazioni entro certi limiti, si può fare a meno del Jet le funzionalità DAO ISAM-oriented non sono supportate E’ l’unica interfaccia di automazione inclusa in Office che consenta di accedere a fonti dati ODBC senza passare per Jet Office non contiene la licenza d’uso e di ridistribuzione di RDO

DAO: ODBCDirect Workspace OM

RDO qualsiasi fonte ODBC paradigma ad oggetti efficiente per usare fonti ODBC non supporta interfacce a tabelle o DDL scongliato con ISAM efficiente, rapido e lightweight verso database relazionali asincrono e event-driven

SQLDMO paradigma ad oggetti su Microsoft SQL Server una soluzione specifica per il client/server via Automation con SQL-Server veloce e lightweight

ADO qualsiasi fonte ODBC e tutte quelle disponibili via OLE DB supporto solo a 32 bit Incluso in MDAC X.Y Si tratta di uno strato SW sopra ad OLEdb

ADO: Oltre i database, tutti i tipi di dati Database aziendali File system Elaborazioni di dati ISAM Strutture dati personali Fogli elettronici Pianificazione di progetti E-mail Directory services... Presentati sotto forme diverse: Suoni Grafici Video Immagini Stream continui Dati relazionali

Architettura a componenti di OLE DB Consumer Un consumer usa i dati forniti dal provider Il provider può accedere ai dati di una fonte dati o fare da consumer di altri dati Tutto basato su interfacce COM standard Provider Data source

Il modello relazionale di OLE DB OLE DB è un set di oggetti Ogni oggetto implica più interfacce correlate Il provider può non supportare tutte le interfacce di un oggetto Data source proprietà Session “Hstmt” Transaction query Rowset Command acquisizione dati Rowset

Il modello di ADO Un set semplificato, non gerarchico Elevate prestazioni, facilità d’uso Si presenta come un OLE DB Consumer Accessibile da C++, Visual Basic®, Java™, VBScript, VBA, JavaScript, C# Da C++ si può ottenere sia oggetti ADO che OLE DB, o entrambi Connection Command Parameters Recordset Fields Errors

Usare ADO con VBScript Predisporre il form Ottenere un recordset <hmtl> tags e oggetti intrinseci </hmtl> Ottenere un recordset <object id=rs classid=”……………."></object> <script language="VBScript"> Provider, DataSource rs.open ………. Visualizzare i dati HTMLObject.Text = rs.Fields(……”).Value Navigare tra i dati rs.MoveNext, rs.MovePrevious

ADO e INTERNET

ODBC e OLE DB ODBC senza OLE DB ODBC con OLE DB Driver manager OLEdb App App App App ODBC API OLE DB Driver manager OLEdb ODBC ODBC ODBC ODBC ODBC driver driver driver driver driver Nessuno strato ulteriore su ODBC

ACCESSO AI DATI CON ADO .NET Maurizio Fermeglia mauf@dicamp.units.it

Perchè ADO.NET è migliore? E’ disconnesso da progetto Relazionale di natura Integrato con XML Il Framework Supporta lo schema reale del Database ADO.NET Connected Access Data Reader ADO.NET Disconnected Access Data Set Data Adapater

Microsoft .NET Framework ADO.NET e .NET Framework Microsoft .NET Framework Web Services User Interface Data and XML ADO.NET XML ... ... Base Classes Common Language Runtime

ADO.NET Overview cos’è ADO.NET? ADO .NET è una collezione di classi, interfaccie, strutture e tipi che gestiscono l’accesso ai dati da fonti relazionali all’interno del .NET Framework Queste collezioni sono organizzate in namespaces: System.Data, System.Data.OleDb, System.Data.SqlClient, etc. ADO .NET è un evoluzione di ADO. Non condivide lo stesso modello ad oggetti, ma condivide molti dei paradigmi e delle funzionalità!

ADO.NET Overview Managed Providers Fonde ADO ed OLEDB in un unico strato Ciascun provider contiene un set di classi che implementano interfacce comuni I ‘managed provider’ implementati: ADO Managed Provider: fornisce l’accesso a fonti dati OLE DB SQL Server Managed Provider: fornisce accesso ottimale quando si utilizzi MS SQL Server Exchange Managed Provider: estrae e modifica dati da Microsoft Exchange

ADO.NET Overview Managed Providers Applicazione ADO.NET Managed Provider SQL Managed Provider ADO Managed Provider OLE DB Provider SQL Server Database Database

ADO vs. ADO.NET ADO Progettato per accessi connessi Totalmente legato al modello fisico dei dati Il RecordSet è il contenitore fondamentael dei dati RecordSet è una (1) tabella che contiene tutti I dati Se si vuole estrarre dati da più di una tabella bisogna fare un database JOIN I dati sono “flattened”: si perdono le relazioni, la navigazione è sequenziale Data types sono legati a COM/COM+ data types Data sharing via COM marshalling (serializzazione) Problemi per il marshalling attraverso I firewalls (DCOM, binary)

ADO vs. ADO.NET cont. ADO.NET Progettato per accessi disconnessi Può modellare I dati a livello logico! Il DataSet rimpiazza il RecordSet DataSet contiene tabelle multiple Estrarre dati da più di una tabella non richiede una JOIN Relationships sono conservate e la naviogazione è realzionale Data types sono legati solo all’XML schema Non è richiesta conversione di data type XML, come HTML, è plaintext: “Firewall friendly”

Benefici di ADO.NET Interoperabilità attraverso l’uso di XML Standard aperto auto descrittivo per I dati Testo leggibile (Human readable) e decifrabile Usato internamente ma accedibile anche esternamente Si può utilizzare XML per leggere, scrivere e muovere dati Scalabilità attraverso il DataSet disconnesso Le connessioni non sono mantenute per lungo tempo Database locking non avviene Supporto al Locking s con ServiceComponents Optimistic locking altrimenti Lavora alla maniera del Web: “Hit and Run!” Maintenibilità Separazione della logica dei dati dalla interfaccia utente

Concetti di base ed architettura Il ADO.NET Object Model Oggetti di System.Data .NET data providers ADO.NET gerarchia dei namespace Organizza il modello ad oggetti Include: System.Data System.Data.OleDb System.Data.Common System.Data.SqlClient System.Data.SqlTypes

ADO.NET- Namespaces System.Data .SqlTypes .SqlClient .Common .OleDb Class Browser per System.data e per System.data.sqlclient

ADO.Net – Introduzione agli oggetti Connection Usato per parlare al DB; le proprietà includono dataSource, username e password SQLConnection e OleDbConnection Command Un SQL statement o Stored Procedure SQLCommand e OleDbComand DataReader: legge solo, una vista unidirezionale dei dati (simile al ADO Recordset) DataSet – oggetto fondamentale per l’accesso ai DB DataView – vista filtrata del DataSet DataAdapter – inizializza le tabelle dei DataSet

Introduzione agli oggetti cont. System.Data Contiene le classi “principali” di ADO.NET In-memory cache dei dati In-memory cache di una tabella del database Usato per manipolare una riga in un DataTable Usato per definire le colonne in un DataTable Usato per relazionare 2 DataTables tra loro Usato per creare viste su DataSets DataSet DataTable DataRow DataColumn DataRelation DataViewManager System.Data Namespace contiene I fondamenti di ADO.NET

DB Connection Esempio-1 <%@ Page Language="vb" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <HTML> <body>

DB Connection Esempio-2 <SCRIPT language="VB" runat="Server"> Sub Page_Load(Src As Object, E As EventArgs) Dim ds As DataSet Dim conn As SQLConnection Dim cmdAuthors As SQLDataAdapter Dim dv As DataView 'create a connection to the Pubs database' conn = New SQLConnection _ ("server=localhost;uid=sa;pwd=super;database=pubs") 'create a dataset with information from the authors table' cmdAuthors = New SQLDataAdapter _("select * from Authors", conn) ds = new DataSet() cmdAuthors.Fill(ds, "Authors") ‘Authors is the DataTable name in ds 'bind the first datagrid to the DefaultView of the dataset' dv = ds.Tables("Authors").DefaultView dgAuthors.DataSource = dv dgAuthors.DataBind() 'create a new DataView that is authors from California' 'and bind the second datagrid to it' dv = New DataView(ds.Tables("Authors")) dv.RowFilter = "state = 'CA'" dgCAAuthors.DataSource = dv dgCAAuthors.DataBind() End Sub </SCRIPT>

DB Connection Esempio-3 <h2>All Authors</H2> <ASP:DataGrid id="dgAuthors" runat="server" Width="700" BackColor="#ccccff" BorderColor="black" ShowFooter="false" CellPadding=3 CellSpacing="0" Font-Name="Verdana" Font-Size="8pt" HeaderStyle-BackColor="#aaaadd"/> <H2>California Authors</H2> <ASP:DataGrid id="dgCAAuthors" runat="server" /> </body> </html>

DB Connection Esempio-4 NOTE: Namespaces incluso in page directives Oggetti usati: SqlConnection ; SqlDataAdapter; Dataset; DataView; Web Form Controls usati: <ASP:DataGrid> Grid.DataBind() moves data from memory (dataview) to web page DataGrid non deve essere legato al dataset; può essere legato ad una hashtable http://jasonc.csse.monash.edu.au/chapter7/datagridsimple.aspx For il codice vedi: http://www.csse.monash.edu.au/courseware/cse2030/2002/datagridsimple.txt

ADO.NET Classi DataSet DataSet DataTable DataColumn DataRow This is a simplified view of the containment relationships in a DataSet. There are actually many other collections and types of objects involved. DataRow DataRelation

Mettendo gli Oggetti assieme… DataSet Tables DataTable DataView DataRow(s) DataColumn Constraint(s) Relations DataRelation DataViewManager DataTable DataTable

Lavorare con I dati - il DataSet Un data cache in-memory dei dati da una fonte dati Un modo comune di rappresentare e manipolare dati Universal data container Non solo da usare con databases Rappresentazione logica o fisica dei dati Progetttato per essere disconnesso dalla fonte dati Connect, execute query, disconnect Può usare XML Per leggere e scrivere dati Per leggere e scrivere XMLSchema

Proprietà e metodi di interesse Collezioni usate per aggiungere e rimuovere tabelle e relazioni Proprietà di interesse: Tabelle: Ritornano le collezioni di oggetti DataTable Relazioni: Ritorna la collezzione di DataRelations Namespace: prende un set di namespace del DataSet Esempio di utilizzo di prorietà: myDataSet.Tables.Add( myTable ); myDataTableCollection = myDataSet.Tables

Il DataTable Può essere mappato ad una tabella fisica nel data source Può essere realzionato ad un’altro tramite DataRelations Impelmenta un modello di optimistic concurrency o locking Proprietà di interesse: Columns: Ritorna ColumnsCollection di DataColumns Rows: Ritorna un oggetto DataRow come una RowsCollection ParentRelations: Ritorna il RelationsCollection Constraints: Ritorna la ConstraintsCollection della tabella DataSet: Ritorna il DataSet del DataTable PrimaryKey: Prende il DataColumns che forma la chaive primaria della tabella

System.Data—DataSet e DataTable Crea un DataTable e lo aggiunge ad un DataSet DataSet ds = new DataSet(); // Create DataTable object: “Customers”. DataTable dt= new DataTable( “Customers” ); // Create and add columns to the table // 1. Explicitly create and Add a DataColumn DataColumn dc; dc = new DataColumn( “CustID”, Type.GetType("System.Int16")); dt.Columns.Add( dc ); // 2. Implicitly Create and Add columns (DataColumn). dt.Columns.Add( “First_Name”,Type.GetType("System String”)); dt.Columns.Add( “Last_Name”, Type.GetType("System String”)); // Add the DataTable object to the DataSet ds.Tables.Add( dt );

DataSet, DataRelation, Data…Views Tables DataView DataTable DataViewManager DataRow(s) DataColumn Constraint(s) Relations DataRelation DataViewSettings DataViewSetting DataViewSetting DataTable DataTable

Viewing Data - il DataView Crea viste multiple sugli oggetti DataTable Collegabile ai controlli dell’interfaccia utente Proprietà di interesse: Table: Estrae o imposta la associata DataTable Sort: prende o imposta le colonne di sort della tabella e l’ordine di sort RowFilter: prende o imposta l’espressione usata per filtrare righe RowStateFilter: prende o imposta lo stato del filtro di riga None, Unchanged, New, Deleted, ModifiedCurrent, ed altri

Creare un DataView: esempio // Code for myTable “Customers” with “Name” column not shown DataView view1 = new DataView( myTable ); DataView view2 = new DataView( myTable ); // Creates Ascending view of Customers by “Name” view1.Sort = “Name ASC”; // Set the view to show only modified (original) rows view2.RowStateFilter= DataViewRowState.ModifiedOriginal; // Bind to UI element(s)... DataGrid myGrid = new DataGrid(); myGrid.SetDataBinding( view1, “Customer”); //...

Viewing + Dati - DataViewManager Simile al DataView ma DataSet oriented Usato per creare viste multiple su un DataSet Permette di settare automaticamente filtri su tabelle Proprietà di interesse: DataViewSettings: prende il DataView per ciascuna DataTable DataSet: prende o imposta il DataSet a cui applicare la view Il metodo CreateDataView Crea un DataView su un DataTable

DataViewManager: un esempio // Create the DataViewManager & views... DataViewManager dvMgr = new DataViewManager( myDS ); dvMgr.CreateDataView( ds.Tables[“Orders"] ); dvMgr.DataViewSettings[“Orders"].Sort = “CustID ASC"; dvMgr.CreateDataView( ds.Tables[“Customers"] ); dvMgr.DataViewSettings[“Customers"].Sort = “Name DESC"; // Bind to a UI elements/controls... dataGrid1.DataSource = viewMgr; dataGrid1.DataMember = "Table1"; dataGrid2.DataSource = viewMgr; dataGrid2.DataMember = "Table2"; // Update the control with the data... dataGrid1.Update(); dataGrid2.Update();

Gli (ADO).NET Data Providers Una collezione di classi per accedere a fonti dati: Microsoft SQL Server™ 200x, SQL Server 7, e MSDE Qualsiasi OLE Database (OLE DB) providers Inclusi: Oracle, JET, e SQL OLE DB Providers Stabilisce connessioni tra DataSets e data stores Due .NET data providers: ADO: via il System.Data.OleDb namespace SQL Server: via il System.Data.SqlClient namespace System.Data.OleDb è il .NET data provider

GErarchia dei .NET Data Providers .Common Contiene classi in comune tra I due System.Data .SqlClient .OleDb SqlCommand SqlConnection SqlDataReader SqlDataAdapter OleDbCommand OleDbConnection OleDbDataReader OleDbDataAdapter

OleDbConnection e SqlConnection Rappresenta una sessione unica con un solo data source Crea, apre, chiude una connessione ad una fonte dati Funzionalità e metodi per gestire transazioni OleDbConnection esempio: String conStr="Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=NWIND_RW.MDB"; OleDbConnection aConn = new OleDbConnection(conStr); aConn.Open(); // Execute Queries using OleDbDataAdapter Class aConn.Close();

ADO.NET - Data Binding Componente chiave delle Web Forms Flessibile e facile da usare Lega la proprietà di un controllo ad informazioni in qualsiasi tipo di data store Provvede controllo sui quanti dati muovere avanti ed indietro Semplice controllo per visualizzare un singolo valore utilizzando tags di collegamento (vedi esempio sotto) <%# %> Controlli complessi per visualizzare una struttura dati ad esempio un datagrid We will cover this when we discuss ASP.NET and Web Forms. <asp:Label id=“SelectedValue”runat=server Text='<%# lstLocation.SelectedItem.Text %>'/>

ADO.NET Classi System.Data.SqlClient Namespace Managed provider nativo per SQL Server Costruito su TDS (Tabular Data Stream) per ottenere alte performance in SQL Server SqlConnection, SqlCommand e SqlDataReader classes Classi per Error handling Connection pooling (implicitamente abilitate per default ) System.Data.SqlTypes fornisce classi per data types nativi di SQL Server

ADO.NET Classi DataSet Esempio string sConnString = “Persist Security Info=False;” + “User ID=sa;Initial Catalog=Northwind;” + “Data Source=MYSERVER”; SqlConnection conn = new SqlConnection(sConnString); conn.Open(); string sQueryString = “SELECT CompanyName FROM Customers”; SqlDataAdapter myDSAdapter = new SqlDataAdapter(); DataSet myDataSet = new DataSet(); myDSAdapter.SelectCommand = new SqlCommand(sQueryString, conn); myDSAdapter.Fill(myDataSet); conn.Close();

Relational Databases Stored Procedure Esempio CREATE PROCEDURE CustOrderHist @CustomerID nchar(5) AS SELECT ProductName, Total=SUM(Quantity) FROM Products P, [Order Details] OD, Orders O, Customers C WHERE C.CustomerID = @CustomerID AND C.CustomerID = O.CustomerID AND O.OrderID = OD.OrderID AND OD.ProductID = P.ProductID GROUP BY ProductName

Stored Procedure Esempio <%@ Page Language="vb" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <HTML> <body> <SCRIPT language="VB" runat="Server"> Dim conn as SQLConnection Sub Page_Load(Src As Object, E As EventArgs) conn = New SQLConnection("server=localhost;uid=sa;pwd=1Aspt;database=conf") displayCategories() displayProducts() displayOrderCount() End Sub

'the ProductCategoryList storedprocedure has no parameters and returns ‘records. display the returned records in a datagrid' Sub displayCategories() Dim cmd As SQLDataAdapter Dim ds As DataSet Dim workParam As SQLParameter = Nothing 'call the ProductCategoryList stored procedure' cmd = New SQLDataAdapter("ProductCategoryList", conn) 'fill dataset with results of stored procedure' ds = new DataSet() cmd.Fill(ds, "Categories") 'bind dataset to datagrid' dgCategories.DataSource = ds.Tables("Categories").DefaultView dgCategories.DataBind() End Sub

'the ProductsByCategory storedprocedure has an input parameter which is the categoryID' 'and returns all items from that category' 'read the input parameter from a text box and display the results in a datagrid' Sub displayProducts() Dim cmd As SQLDataAdapter Dim ds As DataSet Dim workParam As SQLParameter = Nothing 'call the ProductCategory stored procedure' cmd = New SQLDataAdapter("ProductsByCategory", conn) cmd.SelectCommand.CommandType = CommandType.StoredProcedure 'add the CategoryID input parameter from the txtCatID textbox' workParam = New SQLParameter("@CategoryID", SqlDbType.Int) workParam.Direction = ParameterDirection.Input workParam.Value = CInt(txtCatID.Text) cmd.SelectCommand.Parameters.Add (workParam) 'run the stored procedure and fill a dataset with the results' ds = new DataSet() cmd.Fill(ds, "Products") 'bind the dataset to a datagrid' dgProducts.DataSource = ds.Tables("Products").DefaultView dgProducts.DataBind() End Sub

'the OrdersCount stored procedure has an input parameter which is the customerID’ 'and an output parameter which is the number of orders for that customer.''read the input parameter from a text box and display the output value in a label' Sub displayOrderCount() Dim cmd As SQLCommand Dim workParam As SQLParameter = Nothing 'call OrdersCount stored procedure' cmd = New SQLCommand() With cmd .Connection = conn .CommandText = "OrdersCount" .CommandType = CommandType.StoredProcedure End With

'add the CustomerID input parameter from txtCustID textbox' workParam = New SQLParameter("@CustomerID", SqlDbType.Int) workParam.Direction = ParameterDirection.Input workParam.Value = CInt(txtCustID.Text) cmd.Parameters.Add(workParam) 'add the ItemCount output parameter' workParam = New SQLParameter("@ItemCount", SqlDbType.Int) workParam.Direction = ParameterDirection.Output 'open the connection so you can call execute on the SelectCommand' conn.Open() cmd.ExecuteNonQuery() conn.Close() 'display the output parameter in a SPAN element' spnOrderCount.InnerHTML = cmd.Parameters("@ItemCount").Value End Sub </SCRIPT>

<h2>Categories</h2> <asp:datagrid id="dgCategories" runat="server"/> <br><br> <form runat="server"> <P>Enter category: <asp:textbox id="txtCatID" runat="server" Text="14"/> <asp:button runat="server" text="Get Products"/> <h2>Products in Category</h2> <P><asp:datagrid id="dgProducts" runat="server"/> <h2>Number of Current Orders for a Customer</h2> <P>Customer ID <asp:textbox id="txtCustID" runat="server" Text="31"/> <asp:button runat="server" text="Get Order Count"/> <br>has <span id="spnOrderCount" runat="server"></span> outstanding order(s) </form> </body> </html>

Demo Stored Procedure esempio democode/mod03/storedprocedure.aspx Repeater Simple List -repeater Example Utilizza templates per formattare output… (vedi prossime slides)