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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
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
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Senior Product Associate - *Apple* Pay (AME...
…is seeking a Senior Associate of Digital Product Management to support our Apple Pay product team. Labs drives innovation at American Express by originating, Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel 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
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.