ADO Programming with Adaptive Server Anywhere.

Download Report

Transcript ADO Programming with Adaptive Server Anywhere.

EM412
Using Adaptive Server
Anywhere with Visual
Basic
Ali Chalhoub
Technical Support Consultant
iAnywhere Solutions
[email protected]
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.
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
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.
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.
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?
Why Use ADO?
• Easy-to-use interface for data access.
• Current technology
• Low memory overhead, small footprint, high speed
and ease of use.
Connection Flow
VB Application
DAO
ADO
ODBC Direct
Jet
RDO
MS OLE DB
Provider
ODBC
ASA
ASA OLE DB
Provider
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
Using ADO Data Control
To add the ADO Data
control to the toolbox
• Select Components
from the Project
menu.
Using ADO Data Control
• Select Microsoft ADO
Data Control 6.0 (OLE DB).
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
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.
Configuring an ADO Data Control
• Click on the dropdown list for “Use ODBC Data Source Name”.
• Select ASA 7.0 Sample.
Connection Flow
VB Application
ADO
MS OLE DB
Provider
ASA OLE DB
Provider
ODBC
ASA
Configuring an ADO Data Control
• Click on the RecordSource tab.
• Select adCmdTable.
ASA Engine
Configuring an ADO Data Control
• Select customer table from
the “Table or Stored
Procedure Name” option.
• Click on Apply.
• Click on OK.
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”.
Binding a TextBox Control
1) DataSource
2) DataField
Displaying Data
Once all the controls are
bounded, you should be
able to navigate through.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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.
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.
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:
ConnectionString
Value
Provider
ASAProv
UID
User ID
PWD
User Password
ENG
Server Name
DBF
Database File
DBN
Database Name
Links=tcpip{}
host=x.x.x.x
DSN
Data Source Name
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 ).
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
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.
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
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
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
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
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.
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.
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
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
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
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.
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”
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.
Working with Recordset Object
ADO Cursor
Type
ADO constant
Adaptive Server
Anywhere type
Dynamic cursor
adOpenDynamic
Dynamic scroll cursor
Keyset cursor
adOpenKeyset
Scroll cursor
Static cursor
adOpenStatic
Insensitive cursor
Forward only
adOpenForwardOnly
No-scroll cursor
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.
Working with Recordset Object
Recordset Open method syntax:
Recordset-object.Open source, ActiveConection, CursorType, LockType, Options
LockType
Options
It specifies the type of locking the database
should use on the record set when editing of
records occurs.
It tells the database what type the source is.
(I.e adCmdTable, adCmdText,etc..)
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.
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
Working with Recordset Object
CREATE PROCEDURE DBA.GetEmployeesAndDept()
BEGIN
SELECT emp_fname FROM employee;
SELECT dept_name FROM department;
END
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
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.
Working with BLOBS
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
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
Working with Long VarChar
• Saving data of type Long VarChar
Replace(expression, find, replace[, start[, count[, compare]]])
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
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.
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.
Authentication
Authentication
DB
VB
SET OPTION
PUBLIC.DATABASE_AUTHENTICATION='Company=Sybase;Application=BlobsTech;Si
gnature=010fa55157edb8e14d818eb4fe3db41447146f1571g0b8e0330…'
Const ConnectionSignature As String = "SET TEMPORARY OPTION
CONNECTION_AUTHENTICATION='Company=Sybase;Application=BlobsTech;Signatu
re=000fa55157edb8e14d818eb4fe3db41447146f1571g533e0aa19a7cb78153e4…'"
Connection
VB
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
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.
Introduction to ADOCE
• What is ADOCE?
• ADOCE Programming with Adaptive Server
Anywhere.
What is ADOCE?
• ADOCE is a subset of ADO.
• Microsoft has released a new IDE, eVB, to develop for
Windows CE.
Adaptive Server Anywhere OLE
Provider
• Connecting to an ASA Engine.
• Creating Recordsets.
• Navigating Recordsets.
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
Connecting to ASA Engine
Private Sub cmdConnect_Click()
If (ConnectToSybaseDatabase("image")) Then
MsgBox "Connected Successfully!"
End If
End Sub
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
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
Navigating Recordsets
Private Sub loadData()
Private Sub cmdNext_Click()
txtfname.Text = RecSet.Fields(“first_name”).Value
txtlname.Text = RecSet.Fields(“last_name”).Value
txtAddress.Text = RecSet.Fields(“street”).Value
End If
RecSet.MoveNext
If RecSet.EOF Then
RecSet.MovePrevious
End If
Private Sub cmdPrevious_Click()
RecSet.MovePrevious
If RecSet.BOF Then
RecSet.MoveNext
End If
Call loadData
End Sub
Call loadData
End Sub
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
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.