La presentazione è in caricamento. Aspetta per favore

La presentazione è in caricamento. Aspetta per favore

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

Presentazioni simili


Presentazione sul tema: "Maurizio Fermeglia mauf@dicamp.univ.trieste.it ACCESSO AI DATI Maurizio Fermeglia mauf@dicamp.univ.trieste.it."— Transcript della presentazione:

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

2 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

3 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

4 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

5 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

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

7 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

8 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

9 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)

10 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

11 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

12 DAO: Jet Workspace Object Model

13 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

14 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

15 DAO: ODBCDirect Workspace OM

16 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

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

18 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

19 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 Directory services... Presentati sotto forme diverse: Suoni Grafici Video Immagini Stream continui Dati relazionali

20 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

21 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

22 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

23 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

24 ADO e INTERNET

25 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

26 ACCESSO AI DATI CON ADO .NET
Maurizio Fermeglia

27 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

28 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

29 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à!

30 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

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

32 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)

33 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”

34 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

35 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

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

37 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

38 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

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

40 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>

41 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>

42 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 For il codice vedi:

43 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

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

45 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

46 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

47 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

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

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

50 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

51 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”); //...

52 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

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

54 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

55 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

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

57 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 %>'/>

58 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

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

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

61 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

62 '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

63 '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 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

64 '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

65 'add the CustomerID input parameter from txtCustID textbox'
workParam = New SqlDbType.Int) workParam.Direction = ParameterDirection.Input workParam.Value = CInt(txtCustID.Text) cmd.Parameters.Add(workParam) 'add the ItemCount output parameter' workParam = New 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 = End Sub </SCRIPT>

66 <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>

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


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

Presentazioni simili


Annunci Google