TweetFollow Us on Twitter

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.com
http://www.realsoftware.com Valentina
http://www.paradigmasoft.com/ 4D Server
http://www.acius.com/ Oracle
http://www.oracle.com
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.