ACCESSO AI DATI Maurizio Fermeglia [email protected].
-
Upload
sofia-carbone -
Category
Documents
-
view
222 -
download
5
Transcript of ACCESSO AI DATI Maurizio Fermeglia [email protected].
ACCESSO AI DATI
Maurizio [email protected]
11 April 2023 - slide 2
Breve storia dell’Accesso ai DatiVB Objects – API proprietarieData Access Objects (DAO/Jet)Open Database Connectivity (ODBC)OLE for Databases (OLE/DB)ActiveX Data Objects (ADO).NET ADO.NET
11 April 2023 - slide 3
Open Lib
OCI
ODBC
Il concetto di Accesso ai dati
File SystemFile SystemFile SystemFile System
MailMailMailMail
ExcelExcelExcelExcel
IMSIMSIMSIMS
NotesNotesNotesNotes
ProjectProjectProjectProjectData ConsumersData Providers
MAPI
Notes APIProprietary
Proprietary
Proprietary Navigational
Proprietary
OracleOracleOracleOracle
SQL SvrSQL SvrSQL SvrSQL Svr
SybaseSybaseSybaseSybase
Tools & Tools & LanguagesLanguagesTools & Tools &
LanguagesLanguages
11 April 2023 - slide 4
Acesso ai dati con ODBC
File SystemFile SystemFile SystemFile System
MailMailMailMail
ExcelExcelExcelExcel
IMSIMSIMSIMS
NotesNotesNotesNotes
ProjectProjectProjectProjectData ConsumersData Providers
MAPIProprietary
ODBCODBCODBCODBC
OracleOracleOracleOracle
SQL SvrSQL SvrSQL SvrSQL Svr
SybaseSybaseSybaseSybase
Proprietary
SQL EngineSQL EngineSQL EngineSQL Engine
SQL EngineSQL EngineSQL EngineSQL Engine
SQL EngineSQL EngineSQL EngineSQL Engine
DAODAORDORDODAODAORDORDO
Tools & Tools & LanguagesLanguagesTools & Tools &
LanguagesLanguages
11 April 2023 - slide 5
Accesso ai Dati con OLE DB
File SystemFile SystemFile SystemFile System
MailMailMailMail
ExcelExcelExcelExcel
IMSIMSIMSIMS
NotesNotesNotesNotes
ProjectProjectProjectProjectData ConsumersData Providers
OracleOracleOracleOracle
SQL SvrSQL SvrSQL SvrSQL Svr
SybaseSybaseSybaseSybase
ToolsTools
OLEOLEDBDB
OLEOLEDBDB
OLE DBOLE DBOLE DBOLE DB
OLE DBOLE DBOLE DBOLE DB
OLE DBOLE DBOLE DBOLE DB
OLE DBOLE DBOLE DBOLE DB
OLE DBOLE DBOLE DBOLE DB
OLE DBOLE DBOLE DBOLE DB
OLE DBOLE DBOLE DBOLE DB
OLE DBOLE DBOLE DBOLE DB
OLE DBOLE DBOLE DBOLE DB
LanguagesLanguagesDAODAO
ADOADO
11 April 2023 - slide 6
Lo scenario ….
Applicatione
DAO ADO
RDO
ODBC Mgr
ODBC DrvOLEDB
OLEdb-ODBC
JET
ODBCDirect
mdb ISAM SQL Altri…
ADO.NET
11 April 2023 - slide 7
Access: Accesso a dati via ODBC
ODBC Driver Manager
SQL Server ODBC Driver Other ODBC Driver
SQL ServerData Source
Other RelationalData Source
RDO 2.0
ODBCDirect
DAO 3.5
Jet Database Engine
.MDBDatabase
ISAMFiles
Microsoft Access
11 April 2023 - slide 8
La situazione ODBC da un client VB-VC
VBSQLODBC APIDAO/JETDAO/ODBCDirectRDO 2.0SQLDMO
Oppure: ADO ADO .Net
dataJet ODBC
DAO RDO SQLDMO
VBSQLApp
OLEdbADO
11 April 2023 - slide 9
VBSQLMicrosoft SQL Server via DB-Libraryinterfaccia alle API del serveruna delle prime soluzioni per il client/server da applicazioni VBspecifica per SQL-Serverveloce e lightweightsenza interfaccia ad oggettiproblemi di conversione da 16 bit (VBX) a 32 bit (OCX)
11 April 2023 - slide 10
ODBC APIqualsiasi fonte ODBCinterfaccia a ODBC Driver Managerdifficile da utilizzare, proponibile in un numero molto ridotto di casi specificisconsigliabile per l’accesso a ISAMrichiede l’inclusione delle dichiarazioni delle funzionimolto codice da implementare nell’applicazione cliente
11 April 2023 - slide 11
DAO/JETdatabase nativi, ISAM particolari, qualsiasi fonte ODBCparadigma ad oggetti per utilizzare il Jet Enginesui database nativi consente:
DDL (TableDefs, QueryDefs, Relations) DML (Recordsets) sicurezza (Users, Groups) replica (metodi e proprietà)
usato da Access per i propri documenti e oggettilimiti: stored procedure, eventi, cursori server-side
11 April 2023 - slide 12
DAO: Jet Workspace Object Model
11 April 2023 - slide 13
DAO/ODBCDirectqualsiasi fonte ODBCsalta il Jet Engine nelle connessioni a ODBCrichiede RDOnon possiede eventiproblemi di distribuzione (licenze)consente solo operazioni di DMLnato e consigliato per accesso ai dati da Office
11 April 2023 - slide 14
ODBCDirectConsente a DAO di accedere a fonti ODBC tramite RDO invece che tramite JetPer 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
11 April 2023 - slide 15
DAO: ODBCDirect Workspace OM
11 April 2023 - slide 16
RDOqualsiasi fonte ODBCparadigma ad oggetti efficiente per usare fonti ODBCnon supporta interfacce a tabelle o DDLscongliato con ISAMefficiente, rapido e lightweight verso database relazionaliasincrono e event-driven
11 April 2023 - slide 17
SQLDMOparadigma ad oggetti su Microsoft SQL Server una soluzione specifica per il client/server via Automation con SQL-Serverveloce e lightweight
11 April 2023 - slide 18
ADOqualsiasi fonte ODBC e tutte quelle disponibili via OLE DBsupporto solo a 32 bitIncluso in MDAC X.Y Si tratta di uno strato SW sopra ad OLEdb
11 April 2023 - slide 19
ADO: Oltre i database, tutti i tipi di dati
Database aziendaliFile systemElaborazioni di datiISAM Strutture dati personaliFogli elettronici Pianificazione di progettiE-mail Directory services...
Presentati sotto forme diverse:
SuoniGraficiVideoImmaginiStream continuiDati relazionali
11 April 2023 - slide 22
ParametersParameters
CommandCommand
FieldsFields
RecordsetRecordset
ErrorsErrors
ConnectionConnection
Il modello di ADO
Un set semplificato, non gerarchicoElevate prestazioni, facilità d’usoSi presenta come un OLE DB ConsumerAccessibile da C++, Visual Basic®, Java™, VBScript, VBA, JavaScript, C#Da C++ si può ottenere sia oggetti ADO che OLE DB, o entrambi
11 April 2023 - slide 23
Usare ADO con VBScriptPredisporre il form
<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
11 April 2023 - slide 24
ADO e INTERNET
11 April 2023 - slide 25
ODBC senza OLE DBODBC senza OLE DB
AppApp
driverdriver
ODBC
ODBC API
DriverDrivermanagermanager
ODBC
AppApp
ODBC
OLE DB
OLEdb OLEdb ODBCODBC
ODBC
ODBC con OLE DBODBC con OLE DB
AppApp
ODBC e OLE DB
Nessuno strato ulteriore su ODBC
driverdriverdriver driverdriver driverdriver
AppApp
ACCESSO AI DATI CON ADO .NET
Maurizio [email protected]
11 April 2023 - slide 27
Perchè ADO.NET è migliore?E’ disconnesso da progettoRelazionale di natura Integrato con XMLIl Framework Supporta lo schema reale del Database
ADO.NET Connected Access Data Reader
ADO.NET Disconnected Access Data Set Data Adapater
11 April 2023 - slide 28
ADO.NET e .NET Framework
Microsoft .NET Framework
Common Language Runtime
Base Classes
Web Services User Interface
Data and XML
ADO.NET XML ... ...
11 April 2023 - slide 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à!
11 April 2023 - slide 30
ADO.NET OverviewManaged Providers
Fonde ADO ed OLEDB in un unico stratoCiascun 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
11 April 2023 - slide 31
SQL Managed Provider
SQL ServerDatabase
ADO.NET OverviewManaged Providers
ADO.NET Managed Provider
ADO Managed Provider
OLE DB Provider
Database
Applicazione
11 April 2023 - slide 32
ADO vs. ADO.NETADO
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)
11 April 2023 - slide 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”
11 April 2023 - slide 34
Benefici di ADO.NETInteroperabilità 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
11 April 2023 - slide 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
11 April 2023 - slide 36
ADO.NET
ADO.NET- Namespaces
System.Data
.OleDb.SqlClient.SqlTypes .Common
Class Browser per System.data e per System.data.sqlclient
11 April 2023 - slide 37
ADO.Net – Introduzione agli oggettiConnection
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 DataSetDataAdapter – inizializza le tabelle dei DataSet
11 April 2023 - slide 38
Introduzione agli oggetti cont.
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
System.Data
DataTable
DataRow
DataRelation
DataColumn
DataViewManager
DataSet
System.Data Namespace contiene I fondamenti di ADO.NET
11 April 2023 - slide 39
DB Connection Esempio-1<%@ Page Language="vb" %><%@ Import Namespace="System.Data" %><%@ Import Namespace="System.Data.SqlClient" %>
<HTML><body>
11 April 2023 - slide 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>
11 April 2023 - slide 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>
11 April 2023 - slide 42
DB Connection Esempio-4NOTE:
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
11 April 2023 - slide 43
ADO.NET Classi DataSet
DataSet
DataTable
DataRelation
DataRow
DataColumn
11 April 2023 - slide 44
DataSet Tables
DataTable
Mettendo gli Oggetti assieme…
Relations
DataRelation
DataRelation
DataRow(s)
DataColumn
Constraint(s)
DataTable
DataTable
DataView
DataViewManager
11 April 2023 - slide 45
Lavorare con I dati - il DataSet Un data cache in-memory dei dati da una fonte datiUn modo comune di rappresentare e manipolare dati
Universal data container Non solo da usare con databases
Rappresentazione logica o fisica dei datiProgetttato per essere disconnesso dalla fonte dati
Connect, execute query, disconnect
Può usare XML Per leggere e scrivere dati Per leggere e scrivere XMLSchema
11 April 2023 - slide 46
Proprietà e metodi di interesseCollezioni usate per aggiungere e rimuovere tabelle e relazioniProprietà 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
11 April 2023 - slide 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
11 April 2023 - slide 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 DataColumnDataColumn 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 DataSetds.Tables.Add( dt );
11 April 2023 - slide 49
DataViewManager
DataViewSettings
DataSet Tables
DataTable
DataSet, DataRelation, Data…Views
Relations
DataRelation
DataRelation
DataRow(s)
DataColumn
Constraint(s)
DataTable
DataTable
DataView
DataViewSetting
DataViewSetting
11 April 2023 - slide 50
Viewing Data - il DataViewCrea 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
11 April 2023 - slide 51
Creare un DataView: esempio
// Code for myTable “Customers” with “Name” column not shownDataView 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”);
//...
11 April 2023 - slide 52
Viewing + Dati - DataViewManagerSimile al DataView ma DataSet orientedUsato 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
11 April 2023 - slide 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();
11 April 2023 - slide 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
11 April 2023 - slide 55
GErarchia dei .NET Data Providers
System.Data
.OleDb.SqlClient
OleDbCommandOleDbConnectionOleDbDataReaderOleDbDataAdapter
SqlCommandSqlConnectionSqlDataReader
SqlDataAdapter
.Common Contiene classi in comune tra I due
11 April 2023 - slide 56
OleDbConnection e SqlConnection
Rappresenta una sessione unica con un solo data sourceCrea, apre, chiude una connessione ad una fonte datiFunzionalità 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 ClassaConn.Close();
11 April 2023 - slide 58
ADO.NET Classi System.Data.SqlClient Namespace
Managed provider nativo per SQL ServerCostruito su TDS (Tabular Data Stream) per ottenere alte performance in SQL ServerSqlConnection, SqlCommand e SqlDataReader classesClassi per
Error handling Connection pooling (implicitamente abilitate per
default )
System.Data.SqlTypes fornisce classi per data types nativi di SQL Server
11 April 2023 - slide 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();
11 April 2023 - slide 60
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
11 April 2023 - slide 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 SQLConnectionSub Page_Load(Src As Object, E As EventArgs) conn = New
SQLConnection("server=localhost;uid=sa;pwd=1Aspt;database=conf")
displayCategories() displayProducts() displayOrderCount()End Sub
11 April 2023 - slide 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
11 April 2023 - slide 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 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
11 April 2023 - slide 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
11 April 2023 - slide 65
'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 cmd.Parameters.Add(workParam) '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").ValueEnd Sub</SCRIPT>
11 April 2023 - slide 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"/><br><br><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>