Download presentation
Presentation is loading. Please wait.
Published byVivian Irene Goodwin Modified over 9 years ago
1
EM412 Using Adaptive Server Anywhere with Visual Basic Ali Chalhoub Technical Support Consultant iAnywhere Solutions achalhou@sybase.com
2
Using Adaptive Server Anywhere with Visual Basic Visual Basic and its Three Data Interfaces. ADO Programming Using Adaptive Server Anywhere OLE DB Provider. Working with Blobs. Authenticate a Visual Basic Application. Introduction to Windows CE. Summary.
3
Visual Basic and its Three Data Interfaces Visual Basic has three methods to establish a connection with a database. These methods are: DAO RDO ADO
4
Visual Basic and its Three Data Interfaces DAO (Data Access Object) DAO was the first data access technology introduced in Visual Basic. It is used to access desktop databases or remote databases. RDO (Remote Data Object) RDO is used to access remote databases. It is designed to work with client/server databases such as Adaptive Server Anywhere.
5
Visual Basic and its Three Data Interfaces ADO (ActiveX Data Object) ADO is an application programming interface to OLE DB. OLE DB is a low-level interface to all types of data. That’s why it is called Universal Data Access (UDA). OLE DB is a data access model from Microsoft. It uses Component Object Model (COM) interfaces that provide applications with uniform access to data stored in diverse information sources.
6
Visual Basic and its Three Data Interfaces Why use ADO? What is ADO Control? How to Bind Data-Bound Control to an ADO Data Control?
7
Why Use ADO? Easy-to-use interface for data access. Current technology Low memory overhead, small footprint, high speed and ease of use.
8
Connection Flow VB Application DAOADO ODBC Direct RDO ODBC ASA MS OLE DB Provider ASA OLE DB Provider Jet
9
ADO Data Control The ADO data control uses Microsoft ADO to quickly create connections between data-bound controls and data providers. Data-bound controls are any controls that feature a DataSource property. TextBox Labels PictureBox ListBox
10
Using ADO Data Control To add the ADO Data control to the toolbox Select Components from the Project menu.
11
Using ADO Data Control Select Microsoft ADO Data Control 6.0 (OLE DB).
12
Setting up an ADO Data Control Once the ADO Data control is added to the toolbox, the following should be done. Add the ADO control to your form. Set the ConnectionString property. ADO Data Control ADO Data Control Added to the Form
13
Configuring an ADO Data Control To establish a connection from an ADO Data Control to Adaptive Server Anywhere database at design time, the following should be done: Right click the ADO control and select ADODC Properties. Three data source options are available to use. Use Data Link File. Use ODBC Data Source Name. Use Connection String.
14
Configuring an ADO Data Control Click on the dropdown list for “Use ODBC Data Source Name”. Select ASA 7.0 Sample.
15
Connection Flow VB Application ADO ODBC ASA MS OLE DB Provider ASA OLE DB Provider
16
Configuring an ADO Data Control Click on the RecordSource tab. Select adCmdTable. ASA Engine
17
Configuring an ADO Data Control Select customer table from the “Table or Stored Procedure Name” option. Click on Apply. Click on OK.
18
Binding a TextBox Control Once the ADO properties are set correctly, you can bind a data bound control to show data. Add a textbox control to the form where the ADO control was added and set the following properties: Set DataSource to “Adodc1”. Set DataField to “fname”.
19
Binding a TextBox Control 1) DataSource 2) DataField
20
Displaying Data Once all the controls are bounded, you should be able to navigate through.
21
Where Are We? Visual Basic and its Three Data Interfaces. ADO Programming Using Adaptive Server Anywhere OLE DB Provider. Working with Blobs. Authenticate a Visual Basic Application. Introduction to Windows CE. Summary.
22
Adaptive Server Anywhere OLE Provider Introduction to ASA OLE DB Provider. Advantage of using ASA OLE DB Provider. Supported Platforms. Registry Entry. ADO Programming with Adaptive Server Anywhere.
23
Introduction to ASA OLE DB Provider Adaptive Server Anywhere includes an OLE DB provider named ASAProv. This provider is available for windows and windows CE. Adaptive Server Anywhere can also be accessed through Microsoft’s OLE DB provider, MSDASQL, to be used with the Adaptive Server Anywhere ODBC Driver.
24
Adaptive Server Anywhere OLE Provider Introduction to ASA OLE DB Provider. Advantage of using ASA OLE DB Provider. Supported Platforms. Registry Entry. ADO Programming with Adaptive Server Anywhere.
25
Advantage of Using ASA OLE DB Provider Why using Adaptive Server Anywhere is better than Using Microsoft’s generic OLE DB provider? No need to use ODBC in your deployment if ASA OLE DB provider is used. Bookmark is supported when Dynamic cursor is used. Recordcount is supported when Dynamic cursor is used.
26
Adaptive Server Anywhere OLE Provider Introduction to ASA OLE DB Provider. Advantage of using ASA OLE DB Provider. Supported Platforms. Registry Entry. ADO Programming with Adaptive Server Anywhere.
27
Supported Platform The ASA OLE DB provider works with ADOCE 3.0 and later. ADOCE 3.0 is included in the new Windows CE 3.0 devices, such as PocketPC.
28
Adaptive Server Anywhere OLE Provider Introduction to ASA OLE DB Provider. Advantage of using ASA OLE DB Provider. Supported Platforms. Registry Entry. ADO Programming with Adaptive Server Anywhere.
29
Registry Entry When the ASAProv provider is installed, it registers itself. The ASAProv is registered under the following key: HKEY_CLASSES_ROOT\ASAProv If you change the location of your DLL, you must reregister it
30
Registry Entry To register the OLE DB provider: 1.Open a command prompt ( DOS prompt) 2.Change to the directory where the OLE DB provider is installed. (Default C:\Program Files\Sybase\SQL Anywhere 7\win32) 3.Enter the following command to register the provider: Regsvr32 dboledb7.dll
31
Adaptive Server Anywhere OLE Provider Introduction to ASA OLE DB Provider. Advantage of using ASA OLE DB Provider. Supported Platforms. Registry Entry. ADO Programming with Adaptive Server Anywhere.
32
ADO Programming with Adaptive Server Anywhere Connecting to a database using the connection object. Executing statements with the command object. Working with stored procedures. Working with Recordset object.
33
Connecting to a Database Using the Connection Object In order to connect to Adaptive Server Anywhere you must have at least the user id, password and provider. Check the following table: ConnectionStringValue ProviderASAProv UIDUser ID PWDUser Password ENGServer Name DBFDatabase File DBNDatabase Name Links=tcpip{}host=x.x.x.x DSNData Source Name
34
Connecting to a Database with the Connection Object Before the connection can be established, a reference to the ADO library must be set. To set the reference to the library. The following should be done: Select References from the Project Menu. Set a reference to the Microsoft ActiveX Data Object 2.x Library (i.e ActiveX Data Object 2.6 ).
35
Connecting to a Database with the Connection Object Option Explicit Dim adoConn as new ADODB.connection Private Sub cmdConnect_Click() adoConn.Provider = “ASAProv” adoConn.ConnectionString= “uid=dba;pwd=sql;dbf=“ & app.path & “\asademo.db” adoConn.Open End Sub
36
ADO Programming with Adaptive Server Anywhere Connecting to a database using the connection object. Executing statements with the command object. Working with stored procedures. Working with Recordset objects.
37
Executing Statements with the Command Object Option Explicit Dim adoConn as new ADODB.connection Private Sub cmdConnect_Click() Dim adoCmd As New ADODB.Command Set adoCmd.ActiveConnection = adoConn adoCmd.CommandText = "INSERT INTO department VALUES(600,'Accounting',1090)" adoCmd.CommandType = adCmdText adoCmd.Execute End Sub
38
Prepared Statement Improved performance The first time the SQL statement is executed it is parsed and the parsed tree is saved in the engine. At this point, the optimizer generates the execution plan. Correctness of all referenced database objects is verified On subsequent calls, this “ground work” does not have to be repeated
39
Command Object with Prepared Statement Dim adoCmd As New ADODB.Command Set adoCmd.ActiveConnection = adoConn adoCmd.CommandText = "UPDATE employee set emp_fname=?, emp_lname=? WHERE emp_id=?" adoCmd.CommandType = adCmdText adoCmd.Prepared = True Dim prmEmpFName As New ADODB.Parameter Set prmEmpFName = adoCmd.CreateParameter("EmpFName", adChar, adParamInput, 20,txtFirstName.text) adoCmd.Parameters.Append prmEmpFName Dim prmEmpLName As New ADODB.Parameter Set prmEmpLName = adoCmd.CreateParameter("EmpLName", adChar, adParamInput, 20,txtLastName.text) adoCmd.Parameters.Append prmEmpLName Dim prmEmpID As New ADODB.Parameter Set prmEmpID = adoCmd.CreateParameter("EmpID", adInteger, adParamInput,,val(txtEmpID.text) ) adoCmd.Parameters.Append prmEmpID
40
Command Object with Prepared Statement Private Sub cmdUpdate_Click() adoCmd("EmpFName") = txtFirstName.Text adoCmd("EmpLName") = txtLastName.Text adoCmd("EmpID") = Val(txtEmpID.Text) adoCmd.Execute MsgBox "Successfully Updated!" End Sub
41
ADO Programming with Adaptive Server Anywhere Connecting to a database using the connection object. Executing statements with the command object. Working with stored procedures. Working with Recordset objects.
42
Working with Stored Procedures What is a stored procedure? Stored procedure is procedure kept in the database itself which can be called from client application. Stored procedure provides a way of providing uniform access to functions automatically, as the procedure is held in the database, not in each client application.
43
Working with Stored Procedures CREATE PROCEDURE sp_retrieve_contacts() RESULT(id integer,last_name char(15),first_name char(15),title char(2),street char(30),city char(20),state char(2),zip char(5),phone char(10),fax char(10)) BEGIN SELECT id,last_name,first_name,title,street,city,state,zip,phone,fax FROM contact ORDER BY contact.id asc; END
44
Working with Stored Procedures Private Sub cmdExecuteProcedure_Click() Dim adoRS As New ADODB.Recordset adoRS.Open "sp_retrieve_contacts", adoConn, adOpenStatic, adLockReadOnly, adCmdStoredProc adoRS.MoveFirst Set grdData.DataSource = adoRS grdData.Refresh End Sub
45
Error Handling Private Sub ErrorHandler() Dim adoErr as ADODB.Error For Each adoErr In adoConn.Errors strErr = strErr & " Description : " & adoErr.Description & vbCrLf & vbCrLf & _ " SQL CODE : " & adoErr.NativeError & vbCrLf & vbCrLf & _ " SQL STATE : " & adoErr.SQLState & vbCrLf Next MsgBox strErr, vbCritical + vbOKOnly, "Error Connecting" End Sub
46
ADO Programming with Adaptive Server Anywhere Connecting to a database using the connection object. Executing statements with the command object. Working with stored procedures. Working with Recordset objects.
47
Working with Recordset Object What is a Recordset? ADO Recordset is a set of rows. ADO Recordset allows you to set the CursorType property, before you open it. Check the ASA User’s Guide for “Types of Cursor”
48
Working with Recordset Object Recordset Open method syntax: Recordset-object.Open source, ActiveConection, CursorType, LockType,Options Source It could be in-line SQL, stored procedure or table name. ActiveConnection It tells the open method how to access the database. CursorType It tells the database what cursor to use when opening the Recordest.
49
Working with Recordset Object ADO Cursor Type ADO constantAdaptive Server Anywhere type Dynamic cursoradOpenDynamicDynamic scroll cursor Keyset cursoradOpenKeysetScroll cursor Static cursoradOpenStaticInsensitive cursor Forward onlyadOpenForwardOnlyNo-scroll cursor
50
Cursor Types SCROLL cursors remember both rows and row positions within a cursor, so your application can be assured that these positions remain unchanged. DYNAMIC SCROLL cursors are more efficient than SCROLL cursors because they store less information. Therefore, use DYNAMIC SCROLL cursors unless you require the consistent behavior of SCROLL cursors. INSENSITVE cursors has its membership fixed when it is opened; and a temporary table is created with a copy of all the original rows. Fetching from an INSENSITIVE cursor does not see the effect of any other operation from a different cursor. No Scroll cursors restricts fetching operations to fetching the next row or the same row again. Check session AM33 regarding cursors.
51
Working with Recordset Object Recordset Open method syntax: Recordset-object.Open source, ActiveConection, CursorType, LockType, Options LockType It specifies the type of locking the database should use on the record set when editing of records occurs. Options It tells the database what type the source is. (I.e adCmdTable, adCmdText,etc..)
52
Working with Recordset Object Locking types are: Optimistic Locking: The lock is done on row by row basis, when Update is called. Batch Optimistic Locking: The lock occurs when UpdateBatch is called. Pessimistic Locking: The lock is done on the edited records at the data source. Read Only Locking: There is no Locking and the data can’t be changed. Check session EM407 regarding locking.
53
Working with Recordset Object Private Sub cmdOpenRecordSet_Click() On Error GoTo cmdOpenDoubleRecordSet_Err Call GetEmployeesAndDept Call LoadEmployeeName Set adoRS = adoRS.NextRecordset Call LoadDept Call CloseRecordSet Exit Sub cmdOpenDoubleRecordSet_Err: Call ErrorHandler End Sub
54
Working with Recordset Object CREATE PROCEDURE DBA.GetEmployeesAndDept() BEGIN SELECT emp_fname FROM employee; SELECT dept_name FROM department; END
55
Working with Recordset Private Sub GetEmployeesAndDepat() On Error GoTo getEmpAndDept_err Set adoRS = New ADODB.Recordset adoRS.Open "call GetEmployeesAndDept()", adoConn, adOpenStatic, adLockReadOnly, adCmdText Exit Sub getEmpAndDept_err: Call ErrorHandler End Sub Private Sub LoadEmployeeName() lstEmployee.Clear Do While Not adoRS.EOF lstEmployee.AddItem adoRS!emp_fname adoRS.MoveNext Loop End Sub Private Sub LoadDept() lstDept.Clear Do While Not adoRS.EOF lstDept.AddItem adoRS!Dept_name adoRS.MoveNext Loop End Sub
56
Where Are We? Visual Basic and its Three Data Interfaces. Introduction to OLE DB and ADO. ADO Programming Using Adaptive Server Anywhere OLE DB Provider. Working with Blobs. Authenticate a Visual Basic Application. Introduction to Windows CE. Summary.
57
Working with BLOBS
58
Working with Recordset Object Private Sub cmdFetchDirect_Click() If Len(txtPictID.Text) > 0 Then adors.Open "select id, logo from logos where id =" & CInt(txtPictID.Text), adoconn, adOpenDynamic, adLockOptimistic If adors.BOF And adors.EOF Then MsgBox "no record founds" Else Set pctImage.DataSource = adors pctImage.DataField = adors.Fields.Item(1).Name End If adors.Close Set adors = Nothing End If End Sub Private Sub cmdSave_Click() On Error GoTo showError If Len(txtpath.Text) <> 0 Then adocmd.ActiveConnection = adoconn adocmd.CommandText = " INSERT INTO logos(logo) SELECT xp_read_file('" & txtpath.Text & "' )" adocmd.Execute MsgBox "Successfully Inserted" End If Exit Sub showError: MsgBox "Failed to insert" End Sub
59
Working with Recordset Object Private Sub cmdSavedDirect_Click() Dim bytChunk() As Byte Open txtpath.Text For Binary As #1 ReDim bytChunk(FileLen(txtpath.Text)) Get #1,, bytChunk() adors.Open "logos", adoconn, adOpenKeyset, adLockPessimistic, adCmdTable adors.AddNew adors!logo.AppendChunk bytChunk adors.Update adors.Close Set adors = Nothing MsgBox "Successfully Inserted!" Close #1 End Sub
60
Working with Long VarChar Dim strLog As String Set adoCmd = New ADODB.Command 'Escape Character ‘ Replace(txtDoc.Text, " ' ", " ' ' ",,, vbTextCompare) strLog = Replace(txtDoc.Text, "'", "''",,, vbTextCompare) adoCmd.ActiveConnection = adoConn adoCmd.CommandText = "INSERT INTO logs(lognote, logdate) VALUES('" & strLog & "','" & Format(clnDate.Value, "mm-dd-yyyy") & "')" adoCmd.CommandType = adCmdText adoCmd.Execute Saving data of type Long VarChar Replace(expression, find, replace[, start[, count[, compare]]])
61
Where Are We? Visual Basic and its Three Data Interfaces. Introduction to OLE DB and ADO. ADO Programming Using Adaptive Server Anywhere OLE DB Provider. Working with Blobs. Authenticate a Visual Basic Application. Introduction to Windows CE. Summary.
62
Authentication The Authenticated Edition of ASA is provided for Sybase Commercial Application Partners. Applications that use the authenticated engine/server, and are not authenticated, are limited in the functions they can carry out. Every connection must be authenticated and has thirty second grace period before the restrictions apply. Authentication is not a security device.
63
Authentication
64
Function Authenticate(tempadoConn As ADODB.Connection) As Boolean Dim adoCmd As New ADODB.Command adoCmd.CommandText = ConnectionSignature adoCmd.CommandType = adCmdText adoCmd.ActiveConnection = tempadoConn adoCmd.Execute Authenticate = True End Function Const ConnectionSignature As String = "SET TEMPORARY OPTION CONNECTION_AUTHENTICATION='Company=Sybase;Application=BlobsTech;Signatu re=000fa55157edb8e14d818eb4fe3db41447146f1571g533e0aa19a7cb78153e4…'" SET OPTION PUBLIC.DATABASE_AUTHENTICATION='Company=Sybase;Application=BlobsTech;Si gnature=010fa55157edb8e14d818eb4fe3db41447146f1571g0b8e0330…' VB DB VB Connection
65
Where Are We? Visual Basic and its Three Data Interfaces. Introduction to OLE DB and ADO. ADO Programming Using Adaptive Server Anywhere OLE DB Provider. Working with Blobs. Authenticate a Visual Basic Application. Introduction to ADOCE. Summary.
66
Introduction to ADOCE What is ADOCE? ADOCE Programming with Adaptive Server Anywhere.
67
What is ADOCE? ADOCE is a subset of ADO. Microsoft has released a new IDE, eVB, to develop for Windows CE.
68
Adaptive Server Anywhere OLE Provider Connecting to an ASA Engine. Creating Recordsets. Navigating Recordsets.
69
Connecting to an ASA Engine 1.Create a DSN file. 2.Place the DSN on the root of the CE device. 3.Create the connection string. [ODBC] uid=dba pwd=sql enginename=blob databasename=blob databasefile=\image\blob.db start=\program files\sybase\asa\dbsrv7.exe Image.dsn
70
Connecting to ASA Engine Private Sub cmdConnect_Click() If (ConnectToSybaseDatabase("image")) Then MsgBox "Connected Successfully!" End If End Sub
71
Connecting to ASA Engine Option Explicit Dim Connection Function ConnectToSybaseDatabase(DSNname) 'Create the ADOCE connection object Set Connection = CreateObject("ADOCE.connection.3.1") 'Open the ASA provider Connection.Open "Provider=ASAProv;Data Source=" & DSNname ConnectToSybaseDatabase = True End Function
72
Working with Recordset on CE Dim RecSet Private Sub FetchData() Set RecSet = CreateObject("ADOCE.RecordSet.3.1") RecSet.Open "call sp_retrieve_contacts()", Connection, adOpenKeyset, adLockReadOnly, adCmdText RecSet.MoveFirst Call loadData End Sub
73
Navigating Recordsets Private Sub loadData() txtfname.Text = RecSet.Fields(“first_name”).Value txtlname.Text = RecSet.Fields(“last_name”).Value txtAddress.Text = RecSet.Fields(“street”).Value End If Private Sub cmdPrevious_Click() RecSet.MovePrevious If RecSet.BOF Then RecSet.MoveNext End If Call loadData End Sub Private Sub cmdNext_Click() RecSet.MoveNext If RecSet.EOF Then RecSet.MovePrevious End If Call loadData End Sub
74
Error Handler VBCE doesn’t allow you to have goto label. ADOCE doesn’t allow you to loop through your error object. On Error Resume Next If Err.Number <> 0 then MsgBox “ Error : “ & Err.Number Err.Clear End If
75
Summary ADO, DAO and RDO are the three methods to connect to a desktop or network server database. ASA provider has benefit over the Microsoft provider. Authentication engine requires every connection to be authenticated. ASA supports ADO and ADOCE. ADOCE doesn’t support bound control property. ADOCE is different from the ADO error handler.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.