 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 6.

Slides:



Advertisements
Similar presentations
Basics of Database Programming with VB6
Advertisements

ADO DB in Access VBA © Walter Milner 2005 Slide: 1 ADO VBA Programming in Access.
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
1 Chapter 10 Protecting Data Integrity in a Multiuser Environment.
Chapter 4B: More Advanced PL/SQL Programming
The ADO Data Control. Universal Data Access Open Database Connectivity (ODBC) –standard for accessing data in databases OLE-DB –allows access to data.
ActiveX Data Object ISYS 562. ADO An ActiveX control ActiveX is build upon COM, a contract that defines a standard interface by which objects communicate.
Using Objects and Properties
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall COS 346 Day 23.
Web-based Programming Lanjut Pertemuan 6 Matakuliah: M0492 / Web-based Programming Lanjut Tahun: 2007.
Programming the RecordSet Object
Visual Basic Database Access BICS546. Microsoft Universal Data Access OLE DB: The OLE database protocol –Allows a program to access information in any.
CIS 451: ASP Recordsets Dr. Ralph D. Westfall May, 2002.
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
1 Chapter 8 Object-Based Programming in VBA. 8 Chapter Objectives Declare and use object variables Create procedures that use built-in form methods Find.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
ASP & ADO. Connection Object An implicit connection is created when we open a recordset without a connection object. –rs.open “Customer”, "DSN = Sales”
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
CHAPTER 9 DATABASE MANAGEMENT © Prepared By: Razif Razali.
ADO Recordsets. Recordset Objects Similar to Tables and Queries: data Using VBA/VBScript you… –Open a recordset, –Locate a record –Update or add a record.
Chapter 7 PHP Interacts with Ms. Access (Open DataBase Connectivity (ODBC))
ActiveX Data Object (ADO) in JavaScript J.L.Wang, Yen-Cheng Chen Dept. of Infomation Management Ming-Chuan University Jan
1 VBScript Session What we learn last session?
Introduction to ADO By David R. Stevenson Consulting Software Engineer ABB Automation.
Handling of data from multiple databases. Visual Basic Database Visual Basic application acts as a front-end to the database Visual Basic application.
Copyright © 2001 by Wiley. All rights reserved. Chapter 10: Advanced Database Operations Revising Vintage Videos Setting RecordSource at run time DBGrid.
Irwin/McGraw-Hill Copyright© 2000 by the McGraw-Hill Companies, Inc. PowerPoint® Presentation to accompany prepared by James T. Perry University of San.
Database actions In this presentation… –database actions –database connections –recordsets.
PHP meets MySQL.
Stored Procedures, Transactions, and Error-Handling
Copyright © 2001 by Wiley. All rights reserved. Chapter 9: Introduction to Working with Databases in Visual Basic Database Concepts Relational Database.
Lecture Note 10: Simple Database Techniques. Introduction –Database System –Access, SQL Server and others. –Microsoft Access - Interacting with this databases.
Visual Basic ADO Programming 56:150 Information System Design.
What is database?  Any Method for access info into Application from DataBase?  ODBC is standard for Accessing Data.  Problem with ODBC:  Information.
How to Connect to Database ODBC (Open Database Connectivity) ADO (ActiveX Data Object) ASP Code To Connect to Database Recordset Object Navigating through.
3-Tier Client/Server Internet Example. TIER 1 - User interface and navigation Labeled Tier 1 in the following graphic, this layer comprises the entire.
ActiveX Data Objects (ADO) is Microsoft’s latest database object model. The goal of ADO is to allow VB developers to use a standard set of objects to refer.
Chapter 9 Building the Shopping cart Objective Creating Shopping cart using session Variable. Creating a shopping cart using a database table. Use the.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Microsoft FrontPage 2003 Illustrated Complete Integrating a Database with a Web Site.
INSERT BOOK COVER 1Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall. Exploring Getting Started with VBA for Microsoft Office 2010 by.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Session 1 Module 1: Introduction to Data Integrity
ADO ActiveX Data Object. ActiveX Data Objects (ADO) is Microsoft’s latest database object model. The goal of ADO is to allow VB developers to use a standard.
Visual Basic for Application - Microsoft Access 2003 Finishing the application.
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
Source = Table rsObject.Open tablename, Connection Object, CursorType, LockType, adCmdTable Source = Stored Procedure rsObject.Open stored procedure name,
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 6: Accessing a database with PHP Rob Gleasure robgleasure.com.
ASP-13-1 Recordsets Colorado Technical University IT420 Tim Peterson.
DML Statements contd.. SQL Server CURSORS Cursor is used in handling results of select query for data calculations Cursors are used as buffered.
1 ADO Activex Data Objects. 2 ADO ADO allows users to access data easily from many existing databases (such as Access or Paradox) From ODBC compliant.
ADO & Recordsets. ADO Description & History  ActiveX Data Objects  History  1991 ODBC  Data Access Objects (DAO) for VB developers (JET)  Remote.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
Generating XML Data from a Database Eugenia Fernandez IUPUI.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
 2 Data Object Library approaches ◦ DAO (Data Access Objects)  Original access strategy (up to VB6)  Closely linked to MS Access ◦ ADO (ActiveX Data.
ASP.NET Programming with C# and SQL Server First Edition
Visual Basic Database Access
ADO VBA Programming in Access
Find, filter etc with connection to Access code internally
A Guide to SQL, Seventh Edition
ActiveX Data Objects (ADO)
The Recordset Object.
INT213 Updating the Database.
Error Handling Summary of the next few pages: Error Handling Cursors.
Chapter 10 ASP and Data Store Access
Chapter 8 Advanced SQL.
Presentation transcript:

 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 6

 2004 Tau Yenny, SI - Binus 2 ActiveX Data Object(ADO) Cursor Locking Creating Recordset Filtering Recordset Searching For Records Modifying Records Managing Errors

 2004 Tau Yenny, SI - Binus 3 Cursors Manages the set of records and the current location within the recordset, the latter being handled by the current record pointer. Cursor types:  Static ( adOpenStatic = 3 ). Contain a static copy of the records; meaning that the contents of the recordset are fixed at the time the recordset is created. Any records modified, added, or deleted by other users will not be visible. Movement through the recordset is allowed both forwards and backwards.  Forward Only ( asOpenForwardOnly = 0 ). The default cursor type, which is identical to a Static cursor except that you can only move forwards through the recordset.  Dynamic ( adOpenDynamic = 2 ). Doesn’t have a fixed set of records. Any changes, additions or deletions by other users will be visible in the recordset. Movement through the recordset is allowed both forwards and backwards.  Keyset ( adOpenKeyset = 1 ). Similar to Dynamic cursors, except that the set of record is fixed. You can see changes by other users, but new records are not visible. If other users delete records, then these will be inaccessible in the recordset. This functionality is achieved by the set of records being identified by their keys – so the keys remain, even if the records change or are deleted.

 2004 Tau Yenny, SI - Binus 4 Cursors Cursor Location  Depends upon the data source.  Certain data source such as Microsoft SQL Server, have a cursor service of their own, whereas others, such as Microsoft Access, don’t have a cursor service.  When open a recordset, you have to choose whether you want the data store to manage your cursor, or OLE DB and ADO to manage the cursor locally for you.  OLE DB has its own cursor service.

 2004 Tau Yenny, SI - Binus 5 Cursors The two options are decided by using the CursorLocation property of either the Connection object or the Recordset object. Set this property to one of two values:  adUseServer – To let the data store manipulate the cursor  adUseClient – To let ADO manipulate the cursor Set this property before open the connection or recordset. Or conn.CursorLocation = adUseServer conn.Open strConn rsAuthor.CursorLocation = adUseClient rsAuthor.Open “authors”, conn

 2004 Tau Yenny, SI - Binus 6 Cursors The default cursor is server-based. Server cursor – the data store is responsibility to manage the records. Client cursor – managed by the local client cursor service and the entire contents of the recordset are copied onto the client.

 2004 Tau Yenny, SI - Binus 7 Locking Locking is how we ensure the integrity of our data, making sure that changes aren’t overwritten. We need to avoid the classic lost update situation; where one user changes some data, and then another user changes it immediately afterwards. To manage this protection we lock records, just like we lock our house, and there are several different methods of ensuring that records are protected.

 2004 Tau Yenny, SI - Binus 8 Locking Lock Types  Read Only ( adLockReadOnly = 1 ). The default locking type, which means the recordset is read-only, and records cannot be modified.  Pessimistic ( adLockPessimistic = 2 ). When amending a record, the provider will try to lock the record to guarantee the successful editing of the record. This is generally accomplished by locking the record as soon as editing takes place.  Optimistic ( adLockOptimistic = 3 ). The record is not locked until the changes to the record are committed to the data store, by way of the Update method.  Batch Optimistic ( adLockBatchOptimistic = 4 ). Batch optimistic locking allows multiple records to be modified, and the records are only locked when the UpdateBatch method is called.

 2004 Tau Yenny, SI - Binus 9 Locking When you don’t need to modify any records, use a Read-Only recordset. For general use, Optimistic is probably best, since the data store only locks the record for a small period of time – whilst it’s actually updating the data. This reduces the resources used. Pessimistic locking increases data integrity, but at the cost of concurrency. This is the ability of many users to view the data at once. A locked record is not available for viewing by other users, therefore concurrency is reduced. Optimistic locking locks the record for a shorter period of time and therefore increases concurrency, but there’s a greater chance of the data being modified by others.

 2004 Tau Yenny, SI - Binus 10 Creating Recordsets Creating a recordset is achieve by the open method of the Recordset object Recordset.Open [Source], [ActiveConnection], [LockType], [Options] ArgumentDescription SourceThe source of the data. This can be the name of the table from a database, a stored query or procedure, a SQL string, a Command object, or any other command applicable to the Provider. ActiveConnectionThe connection to use for the recordset. This can be a connection string or an open Connection object. CursorTypeThe type of cursor to use. This must be one of the defined cursor types. The default is adForwardOnly. LockTypeThe type of locking to use. This must be one of the defined lock types. The default is adLockReadOnly. OptionsTells the provider what the Source argument is – that is, whether it is a table, a text string, and so on.

 2004 Tau Yenny, SI - Binus 11 Creating Recordsets For example, to open a recordset on the authors table in the pubs database: Dim rsAuthors Set rsAuthors = Server.CreateObject(“ADODB.Recordset”) rsAuthors.Open “authors”, strConn ‘ Do something here rsAuthor.Close Setrsauthors = Nothing Notice that several of the arguments have been left off. In fact, all of the argument are optional, and you could set their corresponding properties before opening the recordset: Dim rsAuthors Set rsAuthors = Server.CreateObject(“ADODB.Recordset”) With rsAuthors.Source = “author”.ActiveConnection = strConn.CurcorType = adOpenForwardOnly.LockType = adLockReadOnly.Open End With ‘ Do something here rsAuthor.Close Setrsauthors = Nothing

 2004 Tau Yenny, SI - Binus 12 Creating Recordsets Once the recordset has been opened, you are automatically placed on the first record. If there are no records in the recordset, then both BOF and EOF properties will be True rsAuthors.Open “authors”, strConn If rsAuthors.BOF and rsAuthors.EOF Then ‘ Recordset is empty End If

 2004 Tau Yenny, SI - Binus 13 Creating Recordsets The Option Argument Allows to specify what the command text contains. It can be one of the following CommandTypeEnum constants:  adCmdText (1)– To Indicate a text command, such as a SQL String  adCmdTable (2) – To indicate the name of a table  adCmdStoredProc (4) – To indicate the name of a stored procedure  adCmdFile (256)– To Indicate the file name of a saved recordset  adCmdTableDirect (512)– To indicate the name of a table  adCmdURLBind – To indicate a URL The difference between adCmdTable and adCmdTableDirect is small, but if you want all columns from a table, then adCmdTableDirect is marginally faster, as ADO performs some internal optimization. There are also 2 other options: adCmdUnspecified (-1), indicating that no type is specified, and adCmdUnknown (8), indicating that the command type is unknown. In general you won’t probably use this.

 2004 Tau Yenny, SI - Binus 14 Creating Recordsets Additional Options The option argument can be one of the previous constants, but you can also add in one of the following ExecuteOptionEnum constants:  adAsyncExecute (16)– To indicate the command should be executed asynchronously  adAsyncFetch (32)– To indicate that after the initial set of rows has been fetched, and remaining rows are fetched asynchronously  adAsyncFetchNonBlocking (64)– Similar to adAsyncFetch, except that the fetching of records never blocks commands  adExecuteNoRecords (128)– To indicate that the command does not return any records Asynchronous processing means that the actions happen in the background; so instead of running a command and waiting for it to finish (synchronously), you can run the command, and then carry on doing something else, whilst the command is executing in the background.

 2004 Tau Yenny, SI - Binus 15 Creating Recordsets The adExecuteNoRecords option is extremely useful. It tells ADO that the command you are executing does not return any data; therefore, there is no point in building a recordset. This can be speed up action queries. To add one of this options you can use the Or statement (Or = +) Moving Through the Recordset  MoveFirst  MoveNext  MoveLast  MovePrevious adCmdStoredProc Or adExecuteNoRecords adCmdStoredProc + adExecuteNoRecords

 2004 Tau Yenny, SI - Binus 16 Filtering Recordsets Filtering is a way of temporarily restricting the view of records in a recordset. Filtering with a Criteria The Filter property takes a variety of arguments, one of which is a criterion very much like a SQL WHERE clause: rsAuthors.Filter = “au_lname = ‘Homer’ or au_lname = ‘Francis’ ” rsAuthors.Filter = “au_lname LIKE ‘Ho%’ ” rsAuthors.Filter = “state = ‘ca’ ” rsAuthors.Filter = “” Use the empty string to reset (clean) the filter, so that all records are once again shown:

 2004 Tau Yenny, SI - Binus 17 Filtering Recordsets Filtering with a Constant  adFilterNone (0)– To remove the current filter. This has the same effect as using an empty string.  adFilterPendingRecords (1)– To view only records that have changed, but have not yet been sent to the server. This only applicable in batch update mode.  adFilterAffectedRecords (2)– To view only records affected by the last Delete, Resync, UpdateBatch or CancelBatch method call.  adFilterFetchedRecords (3)– To view records in the cache. This means the results of the last method call to retrieve records.  adFilterConflictingRecords (5)– To view records that failed to update during the last batch update.

 2004 Tau Yenny, SI - Binus 18 Filtering Recordsets Filtering with Bookmarks The last method of filtering recordsets is to use an array of bookmarks. This allow you to build up a list of records, and then at a later date apply a filter. rsAuthors.Open “authors”, strConn, adOpenKeyset, adLockReadOnly, adCmdTableDirect avarBkmk(0) = rsAuthors.Bookmark ‘Save bookmark for the first record rsAuthors.MoveNext ‘Move forward two records rsAuthors.MoveNext avarBkmk(1) = rsAuthors.Bookmark ‘Save Bookmark for the third record rsAuthors.MoveLast‘Move to the end and save the bookmark avarBkmk(2) = rsAuthors.Bookmark rsAuthors.Filter = Array (avarBkmk(0), avarBkmk(1), avarBkmk(2))‘Now apply the filter While Nor rsAuthors.EOF‘Now loop through the recordset Response.Write rsAuthors (“au_lname”) & “ ” rsAuthors.MoveNext Wend

 2004 Tau Yenny, SI - Binus 19 Searching For Records Searching for individual is performed with the “Find” method. Also can use optional arguments to specify some extra option. If the record isn’t found, then the position is in one of two places : rsAuthors.Find “au_lname=‘Lloyd’” Recordset.Find Criteria, [SkipRows], [SearchDirection], [Start] SkipRows indicating the number of rows to skip before starting the search (default 0). SearchDirection can be either adSearchForward or adSearchBackward Start identifying the position from which to start the search. If Searching forwards, position is after the end of the recordset, and EOF is set If Searching backwards, position is before the start of the recordset, and BOF is set

 2004 Tau Yenny, SI - Binus 20 Searching For Records Using Bookmarks to Save the Position This re-positioning when records are not found is one place where bookmarks come in handy, since the current position bookmarked, search for a record, and if not found, move back to the saved position. ‘Save the bookmark position varBkmk = rsAuthors.Bookmark ‘Find the record rsAuthors.Find “au_lname = ‘Sussman’” ‘Was it found If Not rsAuthors.EOF Then Response.Write “Found: “ & rsAuthors(“au_lname”) & “, “ & rsAuthors(“au_fname”) & “ Else Response.Write “Not found. Moving ” rsAuthors.Bookmark = varBkmk End If

 2004 Tau Yenny, SI - Binus 21 Modifying Records Using the Recordset object’s methods, can use a locking type other than adLockReadOnly to be able to change the data. The default locking type is read-only Modifying can be :  Adding Records  Editing Records  Deleting Records

 2004 Tau Yenny, SI - Binus 22 Modifying Records Adding Records  There are two ways of using this.  The first (simply adds a new record, setting the four mandatory fields) With rsAuthors.Open “authors”, strConn, adOpenDynamic, adLockOptimistic, adCmdTableDirect.AddNew.Fields(“au_id”) = “ ”.Fields(“au_lname”) = “Lloyd”.Fields(“au_fname”) = “Janine”.Fields(“contract”) = 0.Update End With

 2004 Tau Yenny, SI - Binus 23 Modifying Records  An alternative way is to use the optional arguments of the AddNew method, which are two arrays – one of the field names and one of the fields values :  This method doesn’t require a call to the Update method. With rsAuthors.Open “authors”, strConn, adOpenDynamic, adLockOptimistic, adCmdTableDirect.AddNew Array (“au_id”, “au_lname”, “au_fname”, “contract” ), _ Array (“ ”, “Lloyd”, “Janine”, 0) End With

 2004 Tau Yenny, SI - Binus 24 Modifying Records Editing Records Similar to the first method of inserting records – the difference being that you don’t need to call the AddNew method strSQL = “SELECT * FROM authors WHERE au_lname=‘Lloyd’” With rsAuthors.Open strSQL strConn, adOpenDynamic, adLockOptimistic, adCmdText.Fields(“contract”) = 1.Update End With

 2004 Tau Yenny, SI - Binus 25 Modifying Records Deleting Records  To delete records, call the Delete method.  The optional argument, can be one of the AffectEnum constants adAffectCurrent (1)– to indicate only the current record is deleted. This is the default action. adAffectGroup (2)– to indicate that all records matching the current filter are deleted. adAffectAll (3)– to indicate all records in the recordset are deleted. adAffectAllChapters (4)– to indicate that records in all chapters are deleted. rsAuthors.Delete rsAuthors.Delete adAffectGroup

 2004 Tau Yenny, SI - Binus 26 Managing Errors The Errors Collection  Contains an Error Object for each error that occurred during a single ADO command.  Multiple errors may be occur during a command, and the OLE DB provider needs a way to inform the client that more than one error has occurred.  Two important points: Each time ADO command is run, if an error occurs, the Errors collection is cleared and filled with the new details. However, if no error occurred, the Errors collection is not touch. Therefore the collection may contain errors even though the ADO command completed successfully. The OLE DB Provider may fill the Errors collection with informational messages or warnings, which will have an error number of 0. Therefore you cannot just check the number of errors in the collection and assume that an error has occurred.

 2004 Tau Yenny, SI - Binus 27 Managing Errors The Errors collection is only accessible from the Connection object. If you haven’t explicitly created a Connection object, the Recordset object has an ActiveConnection property, which contains the Connection object for the current Recordset. You can get the Errors collection like so: To see all errors that occur, loop through the collection: rsAuthors.ActiveConnection.Errors For Each errAuthorss In rsAuthors.ActiveConnection.Errors ‘ Display error Next

 2004 Tau Yenny, SI - Binus 28 Managing Errors Properties of the Error object PropertyDescription NumberThe ADO error number NativeErrorThe error number from the data provider SQLStateThe 5 digit SQL state code for the error, when connecting to SQL databases SourceThe object that generated the error DescriptionDescriptive text of the error For Each errAuthorss In rsAuthors.ActiveConnection.Errors Response.Write “Number: “ & errAuthors.Number & _ “ NativeError: “ & errAuthors.NativeError & _ “ SQL State: “ & errAuthors.SQLState & _ “ Source: “ & errAuthors.Source & _ “ Description: “ & errAuthors.Description& _ “ ” Next

 2004 Tau Yenny, SI - Binus ADO Errors in ASP Page <% 8.On Error Resume Next ‘ The best way to check for errors 9. strSQL = "SELECT missColumn1,missColumn2, au_lname, au_fname FROM authors" 10.set rsAuthors = Server.CreateObject("ADODB.REcordset") 11.rsAuthors.Open strSQL, conn 12.If CheckForErrors(rsAuthors.ActiveConnection) = False then 13. While Not rsAuthors.EOF 14. Response.Write rsAuthors("au_lname") & ", " & rsAuthors("au_fname") & " " 15.rsAuthors.MoveNext 16. Wend 17.End if 18.rsAuthors.Close 19.Set rsAuthors = Nothing 20.%> 21.

 2004 Tau Yenny, SI - Binus Function CheckForErrors(objConn) 24. Dim objError'Error Object If objConn.Errors.Count >0 Then‘Errors means the count will be greater than For Each objError in objConn.errors 28. If objError.Number<>0 Then 'Errors with number 0 are informational 29. Response.Write " " & _ 30. " Error Property Contents " & _ 31. " Number " & objError.Number & " " & _ 32. " NativeError " & objError.NativeError & " " & _ 33. " SQLState " & objError.SQLState & " " & _ 34. " Source " & objError.Source & " " & _ 35. " Description " & objError.Description & " " 36. CheckForErrors = True 37. End If 38. Next Else CheckForErrors = False 43. End If 44.End Function

 2004 Tau Yenny, SI - Binus 31 ADO Errors in ASP Page