You are on page 1of 20

eVB Development

Intro to Pocket PC databases


Written by Derek Mitchell (derek@deVBuzz.com) Download code available at http://www.deVBuzz.com/downloads/database1.zip Well this is always a good litmus test of your development aptitude - just how long it takes to try setting up a database in any new application environment. If you are itching to get to that stage this is just the tutorial for you. This simple tutorial will show you how to add and delete a database, create and drop tables and insert data into a table. What you need to get started
?? install eMbedded Visual Tools ?? Pocket PC docked

Creating the Project


For this tutorial I'm going to depart from previous formats and make the project source available for download. This way we can fast-track creating the project and I can walk you through the code. I'm presuming at this stage of development you have mastered the techniques of adding Project components and references. For this project we will need to select the CE ADO control and the CE File System control references. In addition you will need to add the CE File System control to the project.

Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 1 of 20

eVB Development

Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 2 of 20

eVB Development
Project Overview
After downloading and running the eVB project on your Pocket PC you should see the following screen:

The general idea here is that each of the command buttons will perform a discrete task. In this tutorial we will:
?? create a database ?? create a table ?? insert rows into the table ?? delete the table ?? finally delete the database

For each of the above tasks we will walk through the code. There is limited error trapping in this demo, the goal is to gain some familiarity with the basic ADOCE objects and methods. Once you have command of these concepts you can perform the task of bomb-proofing the application by catering for any and all contingencies. Let's get started.

Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 3 of 20

eVB Development
Creating an ADOCE database
It's always advisable to create the database before trying to add any records so click the Create DB button. You should now see the following screen:

Now let's take a look at the code that was executed: Private Sub cmdCreateDB_Click() Dim rs, rc 'if it exists ask re deletion If DBExists(gDBFileSpec) = True Then rc = MsgBox("Overwrite database " & gDBFileSpec & " ?", vbYesNoCancel, "Database already exists") If rc = vbYes Then 'clean up current database connection connClose 'delete the file FileSystem1.Kill gDBFileSpec txtDB.Text = gDBFileSpec & " deleted!" Else Exit Sub End If End If
Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 4 of 20

eVB Development
The first thing that we do before creating the database is to check whether the database already exists. If the database already exists then we close the database connection and delete the associated database file name. The database file name and path (filespec) is assigned in the general declaration area of the Form: Const gDBFileSpec = "\My Documents\deVBuzz.cdb". Note we could have used the DROP DATABASE syntax to remove the database, but killing it appealed to me in this instance. Six of one! The DBExists routine simply checks to see whether the database file exists in the CE file system. On to creating the database. 'go ahead and create the database On Error Resume Next Set rs = CreateObject("ADOCE.Recordset.3.0") rs.Open "CREATE DATABASE '" & gDBFileSpec & "'" rs.Close Set rs = Nothing On Error GoTo 0 Now we create the database using the ADOCE recordset object. After we have instantiated the recordset we pass it the filespec of the database we want to create. The filespec includes the path and is mapped from the device root directory. To create the deVBuzz.cdb in the My Documents folder we use '\My Documents\deVBuzz.cdb'. Don't forget the .cdb extension when creating your own databases. To verify the existence of the file use the ActiveSync Explorer to explore the file system on your device. All things being equal you will find the deVBuzz.cdb file in the My Documents folder. If DBExists(gDBFileSpec) = True Then txtDB.Text = gDBFileSpec & " created!" End If End Sub Finally we verify that the database file exists and update our status text.

Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 5 of 20

eVB Development
Creating a table
Now click on the Create Tbl button. You will see the following screen:

Private Sub cmdCreateTbl_Click() ExecSQL "CREATE table TestTable (fldTxt text, fldInt integer)", "TestTable created.", "Err: TestTable was not created." End Sub Looking at the code behind this button we will see that a SQL statement is passed to the ExecSQL routine. We have just created a table in the database using the SQL statement 'CREATE table TestTable (fldTxt text, fldInt integer)'. This table has two fields; the first one called fldTxt will be a text field and the second one an integer field, called strangely enough, fldInt. We now need to look at the ExecSQL routine in order to examine exactly how this request was carried out; but before we do that let's take a quick look at the connOpen routine which opens a connection to the database. Function connOpen() As Boolean On Error Resume Next connOpen = True If conn Is Nothing Then Set conn = CreateObject("ADOCE.Connection.3.0") conn.Open gDBFileSpec If conn.Errors.Count > 0 Then MsgBox "errors in connOpen", vbOKOnly
Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 6 of 20

eVB Development
DispErrors 'connClose connOpen = False End If End If On Error GoTo 0 End Function In this project we are opening and closing database connections each time we perform a database operation. Note that this is an expensive operation timewise and you would normally design your app to batch database operations, but given the nature of this tutorial it makes sense to open and close the database, since each time we open the database connection we are also checking that the database still exists! The connOpen routine ensures we have an open active connection to our database. The conn object in question is the public form variable: Public conn As ADOCE.Connection. This ADOCE connection object is used by all our other ADOCE operations and is the conduit to our database. You will also note the reference to the DispErrors routine and the connClose which we will go into later. Now back to ExecSQL, which in case you have forgotten by now, was the routine that we used to execute out CREATE TABLE SQL. Function ExecSQL(paramSQL As String, paramSuccess As String, paramErr As String) As Boolean If DBExists(gDBFileSpec) = True Then connOpen If the database exists then open a connection to the database. On Error Resume Next conn.Execute (paramSQL) Next we execute the SQL statement using the ADOCE connection object. Using the connection object to execute SQL in this fashion is perfect for those database operations for which we do not expect any return data, as we do here in creating our table. On Error GoTo 0 'check for errors If conn.Errors.Count > 0 Then 'DispErrors ExecSQL = False txtDB.Text = paramErr Else ExecSQL = True
Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 7 of 20

eVB Development
txtDB.Text = paramSuccess End If Next we check the connection Errors collection for any errors. To gracefully handle the errors uncomment the DispErrors reference. connClose Else MsgBox "Database " & gDBFileSpec & " does not exist!", vbOKOnly, "No database" End If End Function Finally we close the connection to the database. Note that we would display the error message parameter passed into the ExecSQL routine if the operation failed. We have created a table called TestTable in our database.

Inserting Rows into TestTable


Click on the Insert Rows button and you will see the following screen:

Turning to the code: Private Sub cmdInsertRows_Click() Dim rs As ADOCE.Recordset Dim arb1 As Integer
Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 8 of 20

eVB Development
If connOpen = True Then Set rs = CreateObject("ADOCE.Recordset.3.0") On Error Resume Next rs.Open "TestTable", conn, adOpenKeyset, adLockOptimistic After creating a connection to the database we instantiate an ADOCE recordset on the TestTable table. For arb1 = 1 To 5 rs.AddNew rs.Fields("fldTxt") = CStr(arb1) rs.Fields("fldInt") = arb1 rs.Update Next Next we iteratively add dummy data to TestTable using the AddNew method of the recordset. Once we have issued the AddNew command we assign values to the recordset fields, referencing the fields collection of the recordset by FieldName ('fldTxt' and 'fldInt'), and assigning them arbitrary values. It is not strictly necessary to call the Update method on the recordset since successive calls to the AddNew method will automatically apply the Update. I have included it here since old habit's die hard and if you don't call it you will lose the data added by the last AddNew transaction. If conn.Errors.Count = 0 Then txtDB.Text = CStr(rs.RecordCount) & " rows were added to TestTable." Else DispErrors txtDB.Text = "There were errors adding rows to TestTable." End If On Error GoTo 0 rs.Close connClose End If End Sub Lastly we check the errors collection of the ADOCE connection for any errors. Again enable or disable the DispErrors routine as you require additional error trapping.

Accessing the data in TestTable


Now that we have a database, with a table and data in the table we may want to access that information. Click on the List Rows button and you should see values from the fldTxt column listed in the the listbox.

Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 9 of 20

eVB Development

Looking at the code below you will see that once more we instantiate an ADOCE recordset object referencing the conn object. Since we only want to read some of the data into the listbox we use a forward only read cursor, traditionally this results in better read performance, however for ADOCE operations this has no performance advantage. We loop through the recordset until the EOF flag is true. I have included code to display either one or all of the recordset fields. Comment out the method you do not want. Also try and use better test data than I have. Private Sub cmdListRows_Click() Dim rs As ADOCE.Recordset Dim cnt As Integer Dim strDisp As String Dim arb2 As Integer If connOpen = True Then List1.Clear Set rs = CreateObject("ADOCE.Recordset.3.0") On Error Resume Next rs.Open "select * from TestTable", conn, adOpenForwardOnly, adLockReadOnly Do While Not rs.EOF 'Method 1 'comment out line below if using Method 2 strDisp = rs(0).Name & ": " & rs(0).Value 'Method 2
Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 10 of 20

eVB Development
'comment out lines below if using Method 1 'add all field data 'strDisp = "" 'For arb2 = 0 To rs.Fields.Count ' strDisp = strDisp & rs.Fields(arb2).Value & " : " 'Next List1.AddItem strDisp rs.MoveNext Loop cnt = rs.RecordCount rs.Close Set rs = Nothing txtDB.Text = cnt & " rows were listed in TestTable." On Error GoTo 0 End If connClose End Sub

Deleting the data in TestTable


What would be the fun in creating all this good stuff if we couldn't tear it all down? Click on the Delete Rows button.

Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 11 of 20

eVB Development
Private Sub cmdDeleteRows_Click() ExecSQL "delete from TestTable", "All rows in TestTable were deleted.", "Err: the rows in TestTable were not deleted." End Sub Again we use the ExecSQL routine to execute SQL using the conn object. In this instance we are not expecting any return data, we just want to delete the table rows using the SQL syntax 'delete from tablename'.

Deleting the table


Click on the Delete Tbl button.

Private Sub cmdDeleteTbl_Click() ExecSQL "DROP table TestTable", "TestTable dropped.", "Err: TestTable was not dropped." End Sub The SQL syntax for removing a table altogether is 'drop table tablename'.

Deleting an ADOCE database


Lastly we delete the database taking us back to the beginning. Now click on the Delete DB button. You will see the following screen:

Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 12 of 20

eVB Development

Private Sub cmdDeleteDB_Click() Dim rc, rs If DBExists(gDBFileSpec) = True Then rc = MsgBox("Delete database " & gDBFileSpec & " ?", vbYesNoCancel, "Delete database")
Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 13 of 20

eVB Development
If rc = vbYes Then 'clean up current database connection connClose 'go ahead and delete the database On Error Resume Next Set rs = CreateObject("ADOCE.Recordset.3.0") rs.Open "DROP DATABASE '" & gDBFileSpec & "'" Set rs = Nothing After confirming that the database file exists and that the user does want to delete it we instantiate an ADOCE recordset and open it with the SQL to delete the database: 'drop database filespec'. There is no need to close the recordset since no data is returned. On Error GoTo 0 Else Exit Sub End If End If If DBExists(gDBFileSpec) = False Then txtDB.Text = gDBFileSpec & " deleted!" End If End Sub That concludes our simple tutorial on how to add and delete a database, create and drop tables and insert data into a table. This is a complete listing of the code for your reference, in addition you can download the project files here. If you have any questions regarding this tutorial please post them in the eVB Databases forum.

General Declarations
Option Explicit Const gDBFileSpec = "\My Documents\drmtest.cdb" Const adOpenForwardOnly = 0 Const adOpenKeyset = 1 Const adOpenDynamic = 2 Const adOpenStatic = 3 Const adLockReadOnly = 1 Const adLockPessimistic = 2 Const adLockOptimistic = 3 Public conn As ADOCE.Connection

Checking whether the database exists


Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 14 of 20

eVB Development
Private Function DBExists(paramFileSpec As String) As Boolean 'this function checks whether the database exists If FileSystem1.Dir(paramFileSpec) <> "" Then DBExists = True Else DBExists = False End If End Function

Create Database
Private Sub cmdCreateDB_Click() Dim rs, rc 'this sub creates a database 'using the gDBFileSpec 'if it exists ask re deletion If DBExists(gDBFileSpec) = True Then rc = MsgBox("Overwrite database " & gDBFileSpec & " ?", vbYesNoCancel, "Database already exists") If rc = vbYes Then 'clean up current database connection connClose 'delete the file FileSystem1.Kill gDBFileSpec txtDB.Text = gDBFileSpec & " deleted!" Else Exit Sub End If End If 'go ahead and create the database On Error Resume Next Set rs = CreateObject("ADOCE.Recordset.3.0") rs.Open "CREATE DATABASE '" & gDBFileSpec & "'" rs.Close Set rs = Nothing On Error GoTo 0 If DBExists(gDBFileSpec) = True Then txtDB.Text = gDBFileSpec & " created!" End If End Sub

Delete Database
Private Sub cmdDeleteDB_Click() Dim rc, rs 'this sub deletes the database
Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 15 of 20

eVB Development
'found at gDBFileSpec If DBExists(gDBFileSpec) = True Then rc = MsgBox("Delete database " & gDBFileSpec & " ?", vbYesNoCancel, "Delete database") If rc = vbYes Then 'clean up current database connection connClose 'go ahead and delete the database On Error Resume Next Set rs = CreateObject("ADOCE.Recordset.3.0") rs.Open "DROP DATABASE '" & gDBFileSpec & "'" 'no need to rs.Close since no rs was returned Set rs = Nothing On Error GoTo 0 Else Exit Sub End If End If If DBExists(gDBFileSpec) = False Then txtDB.Text = gDBFileSpec & " deleted!" End If End Sub

Creating a Table
Private Sub cmdCreateTbl_Click() ExecSQL "CREATE table TestTable (fldTxt text, fldInt integer)", "TestTable created.", "Err: TestTable was not created." End Sub

Inserting Table Rows


Private Sub cmdInsertRows_Click() Dim rs As ADOCE.Recordset Dim arb1 As Integer If connOpen = True Then Set rs = CreateObject("ADOCE.Recordset.3.0") On Error Resume Next rs.Open "TestTable", conn, adOpenKeyset, adLockOptimistic For arb1 = 1 To 5 rs.AddNew rs.Fields("fldTxt") = CStr(arb1) rs.Fields("fldInt") = arb1 rs.Update Next If conn.Errors.Count = 0 Then
Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 16 of 20

eVB Development
txtDB.Text = CStr(rs.RecordCount) & " rows were added to TestTable." Else DispErrors txtDB.Text = "There were errors adding rows to TestTable." End If On Error GoTo 0 rs.Close connClose End If End Sub

Listing the Table Rows


Private Sub cmdListRows_Click() Dim rs As ADOCE.Recordset Dim cnt As Integer Dim strDisp As String Dim arb2 As Integer If connOpen = True Then List1.Clear Set rs = CreateObject("ADOCE.Recordset.3.0") On Error Resume Next rs.Open "select * from TestTable", conn, adOpenForwardOnly, adLockReadOnly Do While Not rs.EOF 'Method 1 'comment out line below if using Method 2 strDisp = rs(0).Name & ": " & rs(0).Value 'Method 2 'comment out lines below if using Method 1 'add all field data 'strDisp = "" 'For arb2 = 0 To rs.Fields.Count ' strDisp = strDisp & rs.Fields(arb2).Value & " : " 'Next List1.AddItem strDisp rs.MoveNext Loop cnt = rs.RecordCount rs.Close Set rs = Nothing txtDB.Text = cnt & " rows were listed in TestTable." On Error GoTo 0 End If
Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 17 of 20

eVB Development
connClose End Sub

Deleting Table Rows


Private Sub cmdDeleteRows_Click() ExecSQL "delete from TestTable", "All rows in TestTable were deleted.", "Err: the rows in TestTable were not deleted." End Sub

Delete the Table


Private Sub cmdDeleteTbl_Click() ExecSQL "DROP table TestTable", "TestTable dropped.", "Err: TestTable was not dropped." End Sub

Form Load Event


Private Sub Form_Load() If DBExists(gDBFileSpec) = True Then txtDB.Text = "The test database has been created." Else txtDB.Text = "Start by creating the database." End If End Sub

Form OK Click Event


Private Sub Form_OKClick() App.End End Sub

ExecSQL
Function ExecSQL(paramSQL As String, paramSuccess As String, paramErr As String) As Boolean If DBExists(gDBFileSpec) = True Then connOpen On Error Resume Next conn.Execute (paramSQL) On Error GoTo 0 'check for errors If conn.Errors.Count > 0 Then 'DispErrors ExecSQL = False
Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 18 of 20

eVB Development
txtDB.Text = paramErr Else ExecSQL = True txtDB.Text = paramSuccess End If connClose Else MsgBox "Database " & gDBFileSpec & " does not exist!", vbOKOnly, "No database" End If End Function

Open a database connection


Function connOpen() As Boolean On Error Resume Next connOpen = True If conn Is Nothing Then Set conn = CreateObject("ADOCE.Connection.3.0") conn.Open gDBFileSpec If conn.Errors.Count > 0 Then MsgBox "errors in connOpen", vbOKOnly DispErrors 'connClose connOpen = False End If End If On Error GoTo 0 End Function

Closing the database connection


Sub connClose() On Error Resume Next conn.Close Set conn = Nothing On Error GoTo 0 End Sub

Displaying Errors
Sub Dim Dim Dim Dim DispErrors() dispErr As String arb1 As Integer arb2 As Integer ADOErr As ADOCE.Error

Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 19 of 20

eVB Development
'show connections errors For arb1 = 0 To conn.Errors.Count - 1 Set ADOErr = conn.Errors(arb1) dispErr = "desc = " & ADOErr.Description & vbCrLf dispErr = dispErr & "number = " & Hex(ADOErr.Number) & vbCrLf dispErr = dispErr & "nativeerror = " & ADOErr.NativeError & vbCrLf dispErr = dispErr & "source = " & ADOErr.Source MsgBox dispErr, vbCritical, strTitleBar Next arb1 End Sub

Version 1 Copyright 2000-2001 deVBuzz.com, Inc., Freehold, NJ. USA.

Page 20 of 20

You might also like