Nov 01 Databases
Volume Number: 17 (2001)
Issue Number: 11
Column Tag: Database Basics
REALbasic Database Basics
by Colin Faulkingham
Introduction
It is hard to find an application today that does not rely on some sort of database. Even on the Macintosh we're seeing an increased use of databases, although some find the state of databases on the Mac to be somewhat behind what you would see on a PC. REALbasic is changing that. Mac users can now join the legions of VB users in creating simple, fast, and effective database applications. REAL Software, Inc. makes databases accessible for the beginner, but also provides the advanced user with powerful tools for connectivity. With REALbasic Professional you can connect to Oracle, 4th, Dimension, PostGreSQL, and ODBC data sources. Valentina has even created a REALbasic Plug-in for using their database technology in REALbasic. For our project we will use the built-in database technology that REAL Software, Inc. has provided: the Real Database. This built-in database is a powerful single user solution that covers the needs of most applications.
Requirements
To build the example project, you will need REALbasic 2.1. If you don't own REALbasic, you can download a 30-day demo version via the web at http://www.realsoftware.com. This article will provide you with the fundamentals for creating and working with databases in REALbasic. It will show you the tools that REALbasic provides for creating database applications quickly and efficiently. This article assumes that you are already familiar with REALbasic.
Getting Started
Let's get started by walking through the application to see what the basic functions need to be. This article will teach you how to create databases dynamically, open databases, query databases, add, update and delete records. First, you should know that there are two ways of working with the Real Database. You can simply create the database using the built-in database schema editor or you can write code that creates your database. Using a database made in the schema editor can be used for the quick application where you could simply reference the database object in your project window. For the purposes of this article you will create a database using code. The application that you will be building will be part of an address book manager for managing your email addresses and phone numbers.
REALbasic uses SQL (structured query language) to create and query your database. You will be using built-in database functions in the form of classes that are built into REALbasic to edit, delete and add records.
Once you know the structure of the database, shown here in Table 1, you can easily create the database document and then add the address table and columns with a simple SQL statement.
Column Name | | Data Type |
ID | | Integer |
FirstName | | Varchar |
LastName | | Varchar |
EmailAddress | | Varchar |
Phone | | Varchar |
Table 1. Creating the database
To create the address table with a SQL statement, do this:
- Launch REALbasic.
- Drag a pushbutton control from the Tools palette on to window1
- Change the caption property of the button to "Create"
- Double-click on the button1 to display the Code Editor
- Choose New Property from the Edit menu
- Type "db as database" in the Declaration field and click the OK button
- Add the database file type by selecting the File Types from the Edit menu, click the Add button, and fill in the necessary data, as shown in Figure 1.
File types are used by you application to define what file type your application will use or create.
Figure 1.
In the Action event handler of the Create button, enter the following code:
Dim dbfile as folderItem
// Create the file reference and and create the database
dbfile=getsaveFolderItem("AddressDB",".rdb")
if dbfile <> nil then
//using the built in function to create the database
db = NewREALDatabase(dbFile)
//Execute the SQL statement to create the table and columns
db.SQLExecute("create table Addresses (Id integer not null, FirstName varchar,
LastName varchar,Email varchar not null,Phone varchar, primary key (Id)")
End If
The code above for this button displays a Save As dialog box, creates a document that will store the database tables and records, and creates the necessary tables and columns that your application will use. While you probably recognize the integer data type, varchar is not so obvious. A varchar column is a column that will store strings/text. As you can see there is a Primary Key reference in the SQL statement; this indicates which column uniquely identifies each row and is a requirement for creating your database. REALbasic will not allow you to create a database without it.
Now choose Run from the Debug menu and click the Create button to create the new file. To check to see if you have actually done it correctly, drop the database file you created into your project window. Double click to view it, using the built-in Schema Editor. Figure 2 shows the list of tables in the Schema Editor and Figure 3 shows the Edit Table window. REALbasic has quite a few column types: varchar, integer, double, smallint, float, Boolean, date and time. The other attribute that you should be aware of is "not null" which tells the database that the corresponding field must contain data. This is extremely important if your application needs to use the data in any particular field for all the records. It also is a requirement for the primary key field.
Figure 2.
Figure 3.
Adding Records
At this point you need to add a couple of items to your window so you can add records to your database.
- Drag a button from the Tools palette to window1.
- Change the caption property of the pushbutton to "New".
- Add the following code the Action event of the New button.
REALbasic's built-in databaserecord class is for creating and accessing records. You will be using it to build a record that you are going to insert into your database table.
Dim rec as databaserecord
//Create a new Record object
Rec=new databaserecord
//You will see that there are various column types in the //databaseRecord class. Column being of the
varchar type.
Rec.column("FirstName")="Steve"
Rec.column("LastName")="Jobs"
Rec.column("Phone")="(111)123-456"
Rec.column("Email")="Sjobs@apple.com"
Rec.integerColumn("Id")=1
//insertrecord is a method of the database class
db.insertrecord("Addresses",rec)
db.commit
You will notice that you are using the commit method of the database class. This method commits the changes to the database. This is essentially a safety net. In a transactional database like the REALdatabase, commit and rollback are used to protect your database. Commit actually makes the changes and the rollback method brings the database back to the state before the last commit was made. Note: REALbasic also has an implicit commit when the user quits the application.
Opening the Database
Before you add these records to the database you need to add a couple more items to your project so you can view the records that you are going to add. Let's add an Open button that will open the database and display all the records in the Addresses table.
- Add another button to Window1 and change its caption to "Open".
- Drag a Listbox into your window.
- In your properties window change the Listbox1 column count to 5
- Make sure your Listbox1 is wide enough to show the columns.
- Drag a DatabaseQuery control in to your window.
REALbasic comes with a DatabaseQuery control that can execute a SQL query and automatically deliver the results of that query into a Listbox or Popupmenu control. You tell the DatabaseQuery control where to put the results of the query using a concept called "binding." Binding lets you connect two controls with an action. One control is the source and the other is the target. In this case, the source is the DatabaseQuery control, which will perform the query, and the target is the Listbox control, which will display the results of the query. To bind the DatabaseQuery control to the Listbox, do this:
- While holding the Command and Shift keys, drag from the DatabaseQuery control to the Listbox control.
- When the New Binding dialog box appears, choose "Bind Listbox1 with list data from DatabaseQuery1 results," as shown in Figure 4.
- Click OK.
Figure 4.
The DatabaseQuery has a couple of properties that you need to be aware of. One is the reference to the database, which is a property of the DatabaseQuery control; since the database is not being referenced in your project you will have to add the database property in code at the time you make the query. Another is the SQL Query. The SQL Query property will hold the SQL query statement that you want the DatabaseQuery control to perform. Now, as you can see in Figure 5, you are going to add the SQLQuery in the Properties window under the Behavior heading for the DatabaseQuery control since you will be executing the same SQL query over and over again.
Figure 5.
"Select FirstName,LastName,Phone,Email,Id from Addresses"
The SQL SELECT statement is most commonly used to choose the columns of data you wish to see from a specific table in the database based on a criterion. You could also use an asterisk, which would indicate that all of the columns should be returned.
To execute the query and display the results in the Listbox, the DatabaseQuery control's RunQuery method must be called. This will cause the DatabaseQuery control to perform the query. Since the DatabaseQuery control is bound to the Listbox, the results from the select statement will display in the Listbox. So, to make the Open button open the database file, perform the query and display the results, enter the following code into the Action event handler of the "Open" button.
Dim f as folderitem
f=getopenfolderitem("addressDB")
//OpenRealDatabase which is a global method to open your REALdatabase
if f<> nil then
db=openRealDatabase(f)
//Execute your query control to update your listbox
DatabaseQuery1.database=db
DatabaseQuery1.runquery
end if
The code above first presents the user with an open dialog and then uses the global method openRealDatabase (File as a Folderitem) to open the database; then a query is made by the DatabaseQuery control. Now from the Debug menu, choose run and click the Open button. Navigate to the database file you created earlier and open it. Click the add button and as you can see in Figure 6, the records you added to your database are displayed in the Listbox automatically.
Figure 6.
Editing and Deleting Records
The next step to building any database application is being able to update and remove records at will. This involves creating a DatabaseCursor, which is not much more difficult than creating a record. A DatabaseCursor is simply a pointer to a set of records returned by a query. It contains the actual rows and columns of data returned by your query. Let's use the spreadsheet in Figure 7 as an example database of 4 addresses. Let's say you performed a query that selected the FirstName, LastName and Phone columns for people whose ID is less than or equal to 2. Figure 8 shows the data would make up the cursor returned by such a query.
Figure 7.
To create the cursor you would need to execute this SQL query
"SELECT FirstName,LastName,Phone From Addresses WHERE Id=2"
Figure 8.
Now that you have a better understanding of what a cursor is you should be ready to manipulate your data. First you need to build your cursor with an SQL statement (note: make sure your SQL statement is on one line, for formatting reasons we cannot show it on one line in this article).
To change the record you created you will need to add an "Edit" button to do that follow these steps.
Add a button to Window1 and change its caption to "Edit"
In the Action event handler for that button insert this code:
Dim updateCursor as databasecursor
updateCursor = db.SQLSelect("select * from Addresses where Email='Sjobs@apple.com'")
//To edit the cursor that you have selected you need to call the
//databasecursor edit method Calling the edit method on a multi-user
//database will lock the necessary tables.
updatecursor.Edit
In the code below, field is returning a cursorfield object and the setstring is a method of that class and is used to change the column in a record. There are a couple of ways you can step through your fields. You can either use the below method of simply referencing the field by name or you can use the IdxField (Index as integer) to reference it by number in a 1-based array.
updateCursor.field("Firstname").setstring "Billy"
updateCursor.field("Lastname").setstring "Jobs"
updateCursor.field("Phone").setstring "(111)000-0000"
updateCursor.field("email").setstring "Bjobs@apple.com"
//Next, you need to call the update method from the DatabaseCursor
//class so that it updates the updateCursor object not the database.
updateCursor.Update
// If you do not use the close method of the databasecursor class REALbasic will do an
//implicit close.
UpdateCursor.close
//commit the changes to the database
db.commit
//run query to update the ListBox
DatabaseQuery1.database=db
DatabaseQuery1.runQuery
Deleting records is a fairly simple operation and it also involves building a databasecursor. After selecting a row, you simply need to call the cursor's DeleteRecord method. Let's add a Remove button that will delete Billy Jobs record:
Drag a new button from your tools palette and make the caption property "Remove"
In your Remove button action event handler insert this code:
Dim cur as databasecursor
//Select a record that is in your database based on your criteria
cur=db.SQLSelect("select * from Addresses where Email ='Bjobs@apple.com'")
//Call the DatabaseCursor DeleteRecord method .
cur.deleteRecord
cur.close
//commit the changes to the database
db.commit
//Run the database query control to update the ListBox results
DatabaseQuery1.database=db
DatabaseQuery1.runquery
Conclusion
The code snippets above are a good starting point, but you really need to get under the hood of the database class and the database cursor class to perform a wide range of functions.
These are the basic functions that you need to create a database driven application. The tools provided in REALbasic are easy enough for a beginner, yet powerful enough to give the advanced user leverage in making production level data-driven applications. If you're planning a commercial or enterprise level application, using the built-in database probably won't cut it; you would probably want to investigate using other databases such as Valentina or a tried and true server such as Oracle or 4D Server. Whatever your database tasks may be you will find REALbasic a pleasure to work with.
References
REALbasic
http://www.realbasic.comhttp://www.realsoftware.com
Valentina
http://www.paradigmasoft.com/
4D Server
http://www.acius.com/
Oracle
http://www.oracle.com