1 VBScript Session 15. 2 What we learn last session?

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.
1 Chapter 12 Working With Access 2000 on the Internet.
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
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.
Mark Dixon Page 1 20 – Web applications: Writing data to Databases using ASP.
CIS 451: ASP Recordsets Dr. Ralph D. Westfall May, 2002.
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 Copyright © 2004, Oracle. All rights reserved. Creating LOVs and Editors.
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.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
Interacting With Data Databases.
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
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
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.
Irwin/McGraw-Hill Copyright© 2000 by the McGraw-Hill Companies, Inc. PowerPoint® Presentation to accompany prepared by James T. Perry University of San.
Using Visual Basic 6.0 to Create Web-Based Database Applications
Database actions In this presentation… –database actions –database connections –recordsets.
Chapter 15: Using LINQ to Access Data in C# Programs.
McGraw-Hill/Irwin Programming in Visual Basic 6.0 © 2002 The McGraw-Hill Companies, Inc. All rights reserved. Update Edition Chapter 11 Accessing Database.
Mark Dixon Page 1 23 – Web applications: Writing data to Databases using ASP.
Working with Numeric Variables (Unit 6) Visual Basic for Applications.
Numeric Variables Visual Basic for Applications 6.
Copyright © 2001 by Wiley. All rights reserved. Chapter 9: Introduction to Working with Databases in Visual Basic Database Concepts Relational Database.
Recordsets Chapter 7. Recordset Objects Similar to Tables and Queries: data But forms cannot be bound to them Fields cannot be bound to them But Access.
XP 1 Microsoft Access 2003 Introduction To Microsoft Access 2003.
ADO 2.5 Kamaljit Bath, Program Manager Data Access Group.
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.
Tutorial 91 Databases A database is an organized collection of related information stored in a file on a disk A database allows companies to store information.
XP New Perspectives on Microsoft Office FrontPage 2003 Tutorial 7 1 Microsoft Office FrontPage 2003 Tutorial 8 – Integrating a Database with a FrontPage.
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.
Lab 8 Data Access Using Microsoft ActiveX Data Object (ADO)
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Database Connectivity What is ADO. What is ADO? ADO is a Microsoft technology ADO stands for ActiveX Data Objects ADO is a Microsoft Active-X component.
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.
What’s new in ADO 2.5 Greg Hinkel Program Manager Data Access Group
What’s new in ADO 2.5 Greg Hinkel Program Manager Data Access Group
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
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.
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.
Dani Vainstein1 VBScript Session 5. Dani Vainstein2 What we learn last session? Branching Branching using If … Then … Else statement. Branching using.
Using databases ActiveX Data Objects (ADO) Connecting to a database Reading data from a database Inserting, updating and deleting records Using databases.
VOCAB REVIEW. A field that can be computed from other fields Calculated field Click for the answer Next Question.
Generating XML Data from a Database Eugenia Fernandez IUPUI.
 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
Data Access Objects .
ADO VBA Programming in Access
ActiveX Data Objects (ADO)
The Recordset Object.
INT213 Updating the Database.
Creating and Modifying Queries
CIS16 Application Programming with Visual Basic
Chapter 10 ASP and Data Store Access
Working With Databases
Presentation transcript:

1 VBScript Session 15

2 What we learn last session?

3 Subjects for session 15  The ActiveX ADODB data model.  Connection Object. Creating a DSN ODBC. Connecting to a database using connection string Connecting to a database using ODBC.  Error Object.  Recordset Object. Querying a database. Opening recordsets in different configurations. Filtering records. Searching for records. Sorting records. Navigating in a recordset. Setting bookmarks. Adding new records.

4 ADODB Object Model Connection Command Recordset ErrorsError ParametersParameter FieldsField

5 ADODB ADODB Object Model  ADODB is a COM object that enables applications to gain access to, and modify a wide variety of data sources.  A data source may be as simple as a text file, complex as a cluster of heterogeneous databases, or a Relational Database.  The typical data source is a relational database that supports the Open Database Connectivity (ODBC) standard and is manipulated with commands written in Structured Query Language (SQL).

6 ADODB Basic ADO Programming Model  ADO provides the means for you to perform the following sequence of actions: 1. Connect to a data source. Optionally, you can ensure that all changes to the data source occur either successfully or not at all. 2. Specify a command to gain access to the data source, optionally with variable parameters, or optionally optimized for performance. 3. Execute the command. 4. If the command causes data to be returned in the form of rows in a table, store the rows in a cache that you can easily examine, manipulate, or change. 5. If appropriate, update the data source with changes from the cache of rows. 6. Provide a general means to detect errors (usually as a result of making a connection or executing a command).

7 ADODB Basic ADO Programming Model  The goal of ADO is to gain access to, edit, and update data sources

8 ADODB ADO Programming Model in Detail  The following elements are key parts of the ADO programming model:  Objects Connection - Enables exchange of data. Command - Embodies an SQL statement. Parameter - Embodies a parameter of an SQL statement Recordset - Enables navigation and manipulation of data. Field - Embodies a column of a Recordset object. Error - Embodies an error on a connection. Property - Embodies a characteristic of an ADO object. In this session we will learn only about the connection and recordset object.

9 ADODB ADO Programming Model in Detail  The following elements are key parts of the ADO programming model:  Collections Errors - All the Error objects created in response to a single failure on a connection. Parameters - All the Parameter objects associated with a Command object. Fields - All the Field objects associated with a Recordset object. Properties - All the Property objects associated with a Connection, Command, Recordset or Field object.

10 ADODB Connection Object  Access from your application to a data source is through a connection, the environment necessary for exchanging data.  Your application can gain access to a data source directly, or indirectly through an intermediary like the Microsoft ® Internet Information Server (IIS).  ADO accesses data and services from OLE DB providers.  The Connection object is used to specify a particular provider and any parameters.

11 Connection Object Connecting to a Data Source  Using a defined DSN (Data Source Name)  Creating a new DSN : Start  Control Panel  Administration Tools  Data Sources

12 Connection Object Creating a user DSN Select user DSN for user DSN or System DSN, for all users Click Add …

13 Connection Object Creating a user DSN Click finish Select Microsoft Access Data driver.

14 Connection Object Creating a user DSN Data Source description ADODB Sample Data source name VBSCourse. Read Only. Click select …

15 Connection Object Creating a user DSN Select file VBS.mdb Click OK

16 Connection Object Connecting to a Data Source Click OK Remark : for user and password click Advanced …

17 Connection Object Creating a user DSN New DSN created.

18 Connection Object Connecting to a database  Using the DSN : Set objConn = CreateObject ( “ ADODB.Connection ” ) objConn.Open “ VBSCourse ”  Using a connection string Set objConn = CreateObject ( “ ADODB.Connection ” ) objConn.ConnectionString = “ Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Class\VBScript\DB\VBS.mdb ” objConn.Open  Or objConn.Open strConnectionString

19 Connection Object Checking the connection  After we activate the method open to te connection, we must check if the connection was succesfull Const adStateOpen = 1 If Not objConn.State = adStateOpen Then Exit.

20 ADODB Connection Object – Errors Collection  Contains all the Error objects created in response to a single failure involving the provider.  Any operation involving ADO objects can generate one or more provider errors.  As each error occurs, one or more Error objects can be placed in the Errors collection of the Connection object.  When another ADO operation generates an error, the Errors collection is cleared, and the new set of Error objects can be placed in the Errors collection.  Each Error object represents a specific provider error, not an ADO error.

21 ADODB Error Object  Contains all the Error objects created in response to a single failure involving the provider.  Any operation involving ADO objects can generate one or more provider errors.  As each error occurs, one or more Error objects can be placed in the Errors collection of the Connection object.  When another ADO operation generates an error, the Errors collection is cleared, and the new set of Error objects can be placed in the Errors collection.  Each Error object represents a specific provider error, not an ADO error.  The set of Error objects in the Errors collection describes all errors that occurred in response to a single statement.

22 ADODB Error Object  Using the error collection, we can describe to the user the specific error. If objConn.State <> adStateOpen Then For Each objErr in objConn.Errors strMsg = "Error #" & objErr.Number & vbCr strMsg = strMsg & “ Desc: " & objErr.Description & vbCr strMsg = strMsg & “ Source: “ & objErr.Source & vbCr strMsg = strMsg & “ State: " & objErr.SQLState & vbCr strMsg = strMsg & “ NativeError: " & objErr.NativeError & vbCr If objErr.HelpFile = "" Then strMsg = strMsg & "No Help file available" & vbCr Else strMsg = strMsg & “ HelpFile: " & objErr.HelpFile & vbCr strMsg = strMsg & “ HelpContext: " & objErr.HelpContext End If Next End If

23 ADODB Error Object  For Example, we try to connect to C:\NotExist.mdb  This is the error message:

24 ADODB Recordset Object  A Recordset object represents the entire set of records from a base table or the results of an executed command.  At any time, the Recordset object refers to only a single record within the set as the current record.  You use Recordset objects to manipulate data from a provider.  When you use ADO, you manipulate data almost entirely using Recordset objects.  All Recordset objects are constructed using records (rows) and fields (columns).  Depending on the functionality supported by the provider, some Recordset methods or properties may not be available.

25 ADODB Queying a Database  For querying a database we will use the Open method of the recordset object.  Syntax: recordset.Open Source, ActiveConnection, CursorType, LockType, Options  Source Indicates the source for the data in a Recordset object (Command object, SQL statement, table name, or stored procedure).  ActiveConnection Indicates to which Connection object the specified Command or Recordset object currently belongs.

26 ADODB Queying a Database  CursorType Indicates the type of cursor used in a Recordset object. Options are:  adOpenForwardOnly – default, you can only scroll forward through records.  adOpenKeyset - you can't see records that other users add, although records that other users delete are inaccessible from your recordset.  adOpenDynamic - Additions, changes, and deletions by other users are visible, and all types of movement through the recordset are allowed.  adOpenStatic - A static copy of a set of records that you can use to find data or generate reports. Additions, changes, or deletions by other users are not visible.

27 ADODB Queying a Database  LockType Indicates the type of locks placed on records during editing. Options are:  adLockReadOnly – Default. Read-only — you cannot alter the data.  adLockOptimistic - Optimistic locking, record by record — the provider uses optimistic locking, locking records only when you call the Update method.

28 ADODB Queying a Database  Options indicates how the provider should evaluate the Source argument. Options are:  adCmdText - textual definition of a command (SQL)  adCmdTable - Indicates that ADO should generate an SQL query to return all rows from the table named in Source.  adCmdTableDirect - Indicates that the provider should return all rows from the table named in Source.  adCmdStoredProc - Indicates that the provider should evaluate Source as a stored procedure.

29 ADODB Querying a database – Example 1 strSQL = “ Select * From Employes Where State= ‘ NY ’” Set objRst = CreateObject( “ ADODB.Recordset ” ) objRst.Open strSQL, objConn While Not objRst.EOF iCounter = iCounter + 1 strRep = “ First Name : “ & objRst( “ EmpFirstName ” ).Value & vbCr strRep = strRep & “ Last Name : “ & objRst( “ EmpLastName ” ).Value & vbCr strRep = strRep & “ Address: “ & objRst( “ EmpAddress ” ).Value & vbCr MsgBox strRep,0, ” Employee “ & iCounter objRst.MoveNext Loop

30 ADODB Querying a database – Example 2 strSQL = “ Select * From Employes Where State= ‘ NY ’” Set objRst = objConn.Execute(strSQL) While Not objRst.EOF iCounter = iCounter + 1 strRep = “ First Name : “ & objRst( “ EmpFirstName ” ).Value & vbCr strRep = strRep & “ Last Name : “ & objRst( “ EmpLastName ” ).Value & vbCr strRep = strRep & “ Address: “ & objRst( “ EmpAddress ” ).Value & vbCr MsgBox strRep,0, ” Employee “ & iCounter objRst.MoveNext Loop

31 ADODB Opening recordsets in different configurations.  For best performance, we are able to open recordset in different configurations.  Usually, in testing, we connecting to databases for search or retrieve data.  In testing, when we reading data, we want to be sure that we are not locking the application.

32 Opening recordsets in different configurations.  The properties LockType and CursorType can assure those requirements.  If we only want to browse a set of records, we set the CursorType to adOpenForwardOnly.  The recommended locktype for testing, is using the flag adLockReadOnly.  Those parameters are the defaults of the properties.

33 Opening recordsets in different configurations - Example strCmd = “ Employes ” Set objRst = CreateObject( “ ADODB.Recordset ” ) objRst.Source = strCmd Set objRst.ActiveConnection = objConn objRst.CursorType = adOpenForwardOnly objRst. LockType = adLockReadOnly objRst.Open,,,, adCmdTableDirect ‘ objRst.Open strCmd,objConn, adOpenForwardOnly, adLockReadOnly, ‘ adCmdTableDirect While Not objRst.EOF iCounter = iCounter + 1 strRep = “ First Name : “ & objRst( “ EmpFirstName ” ).Value & vbCr strRep = strRep & “ Last Name : “ & objRst( “ EmpLastName ” ).Value & vbCr strRep = strRep & “ Address: “ & objRst( “ EmpAddress ” ).Value & vbCr MsgBox strRep,0, ” Employee “ & iCounter objRst.MoveNext Loop

34 Recordset Object Filtering records.  In some cases we want to search several sets of data in a recordset.  We can avoid to open many recordsets several times with other SQL ’ s  Is most efficient, when we have foreign keys.

35 Recordset Object Filter Property  Specifies a filter for data in a Recordset.  Sets or returns a Variant value, which can contain : Criteria string Array of bookmarks FilterGroupEnum values.  Use the Filter property to selectively screen out records in a Recordset object.  The filtered Recordset becomes the current cursor.  This affects other properties, such as AbsolutePosition, AbsolutePage, RecordCount, and PageCount, that return values based on the current cursor, because setting the Filter property to a specific value will move the current record to the first record that satisfies the new value.

36 Recordset Object Filtering records - Example  For example we want to read all the records where the emplyee lives in New York Or in Washington  For this sample, we have already open the record and selected all the employees.  Now we can execute the follow: objRst.Filter = “ City = ‘ New York ’ Or City = ‘ Washington ’”  The new recordset will contain the filtered records.  A run-time error occurs only if there are conflicts on all the requested records. Use the Status property to locate records with conflicts.  Setting the Filter property to a zero-length string ("") has the same effect as using the adFilterNone constant.

37 Recordset Object Searching - Find Method  Searches a Recordset for the record that satisfies the specified criteria.  If the criteria is met, the recordset position is set on the found record; otherwise, the position is set on the end of the recordset.  Syntax recordset.Find (criteria, SkipRows, searchDirection, start)

38 Recordset Object Searching - Find Method  criteria A String containing a statement that specifies the column name, comparison operator, and value to use in the search.  SkipRows An optional Long value, whose default value is zero, that specifies the offset from the current row or start bookmark to begin the search.  searchDirection An optional SearchDirectionEnum value that specifies whether the search should begin on the current row or the next available row in the direction of the search. Its value can be adSearchForward or adSearchBackward. The search stops at the start or end of the recordset, depending on the value of searchDirection.  start An optional Variant bookmark to use as the starting position for the search.

39 Recordset Object Searching - Find Method - Example  Suppose we want to find all the in an already open recordset, all the records where the State of the employee starts with the letter M (i.e Massachusetts)  objRst.Find( “ State Like M* ”,0, adSearchForward)

40 Recordset Object Sorting Records - Sort Property  Specifies one or more field names on which the Recordset is sorted, and whether each field is sorted in ascending or descending order.  Settings and Return Values - Sets or returns a String of comma-separated field names to sort on, where each name is a Field in the Recordset, and is optionally followed by a blank and the keyword ASC or DESC, which specifies the field sort order.  The data is not physically rearranged, but is simply accessed in the sorted order.

41 Recordset Object Navigating in a recordset  We can navigate in a recordset in any desired direction using the MoveFirst, MoveLast, MoveNext, and MovePrevious Methods.  Moves to the first, last, next, or previous record in a specified Recordset object and makes that record the current record.  You can ’ t navigate to previous or first if you open the recordset adOpenForwardOnly flag.  Example : objRst.MoveFirst, objRst.MoveNext

42 Recordset Object Navigating in a recordset BOF JhonErwinNew YorkNY James WalterOlatheKS JennyElliotLos-AngelesCA WillSmithHoustonTX JacobGrahamChicagoIL SaraRobertsAtlantaGR EOF

43 Recordset Object Setting Bookmarks - Bookmark Property  Returns a bookmark that uniquely identifies the current record in a Recordset object or sets the current record in a Recordset object to the record identified by a valid bookmark.  Settings and Return Values - Sets or returns a Variant expression that evaluates to a valid bookmark.  Use the Bookmark property to save the position of the current record and return to that record at any time. Bookmarks are available only in Recordset objects that support bookmark functionality.

44 Recordset Object Setting Bookmarks - Example Dim varBookmark objRst.MoveLast objRst.MovePrevious varBookmark = objRst.Bookmark objRst.MoveFirst objRst.MoveNext objRst.Bookmark = varBookmark

45 Recordset Object Navigating in a recordset – Move Method  Moves the position of the current record in a Recordset object.  Syntax recordset.Move NumRecords, Start  NumRecords - A signed Long expression specifying the number of records the current record position moves.  Start - Optional. A String or Variant that evaluates to a bookmark. adBookmarkCurrent - Default. Start at the current record. adBookmarkFirst - Start at the first record. adBookmarkLast - Start at the last record.

46 ADODB Adding a New Record – AddNew Method Dim iEmpID Dim bSupport If objRst.Supports(adAddNew) Then objRst.AddNew objRst( “ EmpID ” ) = iEmpID objRst( “ fname ” ) = strFirstName objRst( “ lname ” ) = strLastName objRst.Update If Err.Number <> 0 Then MsgBox “ Error adding new record ” End If

47 ADODB Adding a New Record – Example  Usually, in testing, we don ’ t add new records to the database.  The AddNew method Creates a new record for an updatable Recordset object.  Syntax recordset.AddNew FieldList, Values  Use the AddNew method to create and initialize a new record.  Use the Supports method with adAddNew to verify whether you can add records to the current Recordset object.  After you call the AddNew method, the new record becomes the current record and remains current after you call the Update method.

48 ADODB Tips – Using SQL  Use SQL instead of iterative operations.  You can execute queries directly using Execute Example Dim rs Set rs = CreateObject( “ ADODB.Recordset ” ) Rs.Open “ Select * From Users Where …”,conn,3,3 Set rs = conn.Execute( “ Select * From Users Where …” )

49 ADODB Tips - Counting Example rs.Open “ Select * From Users ”,conn,3,3 rs.MoveFirst Do Until rs.EOF If rs( “ State ” ) = “ FL ” Then i = i + 1 rs.MoveNext Loop strSQL = “ Select Count(State) As emp_count From Users Where state= ‘ FL ’” Set rs = conn.Execute(strSQL)

50 ADODB Tips - Searching Example rs.Open “ Select * From Users ”,conn,3,3 rs.MoveFirst Do Until rs.EOF If rs( “ State ” ) = “ FL ” Then bFound = True rs.MoveNext Loop strSQL = “ Select * From Users Where state= ‘ FL ’” Set rs = conn.Execute(strSQL) if Not rs.EOF then bFound = True

51 ADODB Tips - Summing Example rs.Open “ Select * From Users ”,conn,3,3 rs.MoveFirst Do Until rs.EOF iTotal = iTotal + rs( “ Salary ” ) rs.MoveNext Loop strSQL = “ Select Sum(Salary) As total_sal From Users ’” Set rs = conn.Execute(strSQL) MsgBox rs( “ total_sal ” )

52 ADODB Tips - Updating Example Do Until rs.EOF rs( “ Salary ” ) = rs( “ Salary ” ) * 1.05 rs.Update rs.MoveNext Loop strSQL = “ UPDATE Users SET salary=salary*1.05 ’” Set rs = conn.Execute(strSQL)

53 ADODB Tips - Deleting Example Do Until rs.EOF if rs( “ Country ” ) = ‘ UK ’ Then rs.Delete rs.MoveNext Loop strSQL = “ DELETE FROM Users WHERE Country= ‘ UK ’’” Set rs = conn.Execute(strSQL)

54 Lab 15.1  Write an interactive program to navigate in a recordset.  Build a new DNS connection.  An input box should ask the user 1 – Go to the first record. 2 – Go to the next record. 3 – Set a bookmark. 4 – Go to the bookmark. 5 – Go to the previous record. 6 – Go to the last record. 7 – Add a new record.  Be aware of EOF and BOF  Use the table Employees in the Database.  Error handling.

Make sure to visit us  Tutorials  Articles  Proikects  And much more 55