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

Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
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
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer 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 MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.