Some Stored Procedure Examples

This article originally appeared in REALbasic Developer Magazine 4.3 (Jan/Feb 2006)

Now that we know what stored procedures are, let’s take a look at a few more examples. The accompanying Code Listing shows a simple stored procedure for MySQL, PostgreSQL, OpenBase, FrontBase, SQL Server and Oracle. As mentioned last time, the various syntax is similar but also just different enough to be annoying.

How is this related to REALbasic?

REALbasic does not provide a built-in way to call stored procedures, and it provides a nice set of database classes that work with a wide variety of databases. I guess you could say that REALbasic is encouraging you not to use stored procedures at all. That’s not entirely true, but most languages do make it a bit easier to work with them. For example, with VB.NET and ADO.NET you can use the ExecuteNonQuery method to call a stored procedure. Java with JDBC also provides a way to call stored procedures.

In the case of REALbasic, you’ll need to use the appropriate syntax for your database server to call the stored procedure using SQL.

For example, with Microsoft SQL Server (on Windows, connected via ODBC) you would use this code to run a stored procedure called INSERT_TEST:

mySQLServerODBCDatabase.SQLExecute("exec INSERT_TEST")

For Oracle you should enclose the stored procedure call in a block:

Dim spString As String
spString = "BEGIN" + EndOfLine + "INSERT_TEST" + EndOfLine + "END"
myOracleServerDatabase.SQLExecute(spString)

Of course, this technique provides no way for you to easily pass parameters to the procedure and certainly no easy way to get results or parameters back. A workaround for sending parameters would be to insert them directly into the string, which will work for simple datatypes. You could also insert your parameters into a special parameter table and then have the stored procedure look for them there. For return values and results, you could also insert the information into a table and then have your app get it with a SQL SELECT.

Obviously this doesn’t help you a whole lot of you are trying to hook up a REALbasic application to an existing database with stored procedures, which you may not be able to modify. One solution to this dilema is to create new wrapper procedures for the existing stored procedures. Your REALbasic code calls the wrapper which either puts or retrieves the data in the parameter tables and then can call the original stored procedure.

Using JDBC and MonkeyBread

Another option that has recently become available is to use the JDBC classes that are part of the Java plugin included in the MonkeyBread Plugin Suite. It contains a class, JavaCallableStatementMBS, specifically for calling stored procedures. Unfortunately the documentation and examples do not cover this feature well. It looks like you have to set up your parameters individually and then call the procedure using executeQuery.

OpenBase SQL 10

I should note that OpenBase SQL 10 has the ability to create stored procedures using REALbasic. This is not well documented, but apparently REALbasic console applications can be run as stored procedures on the database server.


Stored Procedure Code Samples

Oracle PL/SQL

CREATE PROCEDURE INSERT_TEST AS
BEGIN
INSERT INTO testlog (name, connectTime, status)
VALUES ('Bob Roberts', SYSDATE, 'Active');

COMMIT;

END;

SQL Server T-SQL

CREATE PROCEDURE INSERT_TEST AS
INSERT INTO TestLog (name, connectTime, status)
VALUES ('Bob Roberts', GetDate(), 'Active')

RETURN

GO

PostgreSQL PL/pgSQL

:

CREATE PROCEDURE INSERT_TEST AS
BEGIN
INSERT INTO testlog (name, connectTime, status)
VALUES ('Bob Roberts', now(), 'Active');

COMMIT;

END;

MySQL

CREATE PROCEDURE INSERT_TEST()
BEGIN
INSERT INTO TestLog (name, connectTime, status)
VALUES ('Bob Roberts', CURRDATE(), 'Active');
END

OpenBase OpenScript

START TRANSACTION TRY
REQUIRE EXECUTE SQL "INSERT INTO TestLog (name, connectTime, status) VALUES ('Bob Roberts', CURRDATE(), 'Active')"
REQUIRE COMMIT
CATCH
ROLLBACK
END TRY

FrontBase Stored Procedure

create procedure INSERT_TEST()
BEGIN
INSERT INTO TestLog (name, connectTime, status)
VALUES ('Bob Roberts', CURRDATE(), 'Active');
END;

REALbasic and Cocoa

If you haven’t already received it, the REALbasic Newsletter came out today and it had a little teaser for the upcoming Cocoa functionality.

There’s mention of Mac OS X Leopard-style windows, spell checking and pictures in EditFields, and HUD windows:

D22F16A9-CA67-4540-9D0D-04E7AAC3772B.jpg

Looks pretty slick to me.

To get the newsletter, sign up here.

An Overview of Stored Procedures

This article originally appeared in REALbasic Developer Magazine 4.2 (Nov/Dec 2005)

If you find yourself working with database servers, you may be wondering about stored procedures. Depending on who you talk to, stored procedures are either something you should definitely be using or something you should avoid like the plague. As with most things in life, the answer is not quite so simple.

What is a Stored Procedure?

A stored procedure (SP) is code that runs on the database server. Generally this code is written in a language that is proprietary to the database server you are working with. Some database servers may support more than one store procedure language. Figure 1 is a table of some common database servers and their corresponding stored procedure languages.

I’ll be focusing on the SQL-type programming languages as they are much more commonly used.

Code Listing 1 shows you how a very simple stored procedure looks with PostgreSQL. This is a very simple example that justs inserts a row of data into a log table. The syntax across the various databases is similar, but different enough to be annoying when you work with more than one. They become much less similar when you start working with variable declarations, datatypes and control structures.

As their name implies, stored procedures are procedure-oriented, not object-oriented. They’re not called stored objects, after all. This means there is no support for things like inheritance. Oracle has a little support for data encapsulation with its Stored Packages, but we won’t go into those now. Also note that if you did choose to work with other stored procedure languages, you would get to use object-oriented features, but as I mention above these are not widely used.

Why Should You Use Them?

Stored procedures use a language you probably don’t know and are usually not object-oriented, so why would you consider using them? Well, stored procedures can be quite fast and therefore are frequently used to improve the performance of a database application. Since the code lives right alongside the database, you eliminate almost all network traffic and can allow the database server to work to its fullest.

Another benefit of stored procedures is that they can provide a nice way to encapsulate business logic near the data it is modifying. This can be useful if you expect to have several ways to access data (perhaps both a desktop and web application) and want to ensure a consistent API. It is easier and less error-prone to update this business logic once on the server rather than by updating multiple applications.

Lastly, if you’ve paid a lot of money for expensive database server software, it seems silly to not use all the features it can provide.

Why Should You Avoid Them?

The primary reason to not use stored procedures is that they are not portable. Using stored procedures effectively locks you into using a single database vendor. If you need your application to run on a different vendor’s server, then you’ll need to recreate all your stored procedures. This can be a huge amount of work or can be completely impractical depending on the database servers you use.

Wrapping Up

I’ve worked on projects and products with hundreds of stored procedures, just a few stored procedures, and no stored procedures. The rule I generally follow now is to not rely on stored procedures during initial design and development. I design my applications so that they could work with any database backend. As the product is nearing completion, I review areas that may need performance improvements to see if a stored procedure would make sense . If so, I’ll add the ability to use a stored procedure while at the same time retaining the ability to work without the stored procedure.

Next time we’ll look at more examples of stored procedures using syntax for several different database servers. We’ll also look at how stored procedures can be used with REALbasic.

Simple PostgreSQL PL/pgSQL Stored Procedure

CREATE PROCEDURE INSERT_TEST AS
BEGIN
INSERT INTO testlog (name, connectTime, status)
VALUES ('Bob Roberts', now(), 'Active');

COMMIT;

END;

Figure 1: Databases and Stored Procedure Languages

Database Stored Procedure Language Notes
MySQL SQL:2003 Available starting with V5.0  
PostgreSQL PL/pgSQL, PL/TCL, PL/Perl, PL/Python PL/pgSQL is very similiar to Oracle PL/SQL
Oracle PL/SQL, Java
SQL Server Transact-SQL (T-SQL), C#, VB.NET C#, VB.NET available in SQL Server 2005
OpenBase OpenScript, Java, REALbasic
FrontBase Stored Procedures
DB2 Procedural SQL, Visual Basic .NET, C, C++, C#, COBOL, Java, or REXX

Database Servers: FrontBase

This article was originally published in REALbasic Developer 6.1 (Nov/Dec 2007)

FrontBase is a full-featured database server that is available for Mac OS X, Linux and Windows. It was created by a Denmark company and was initially release just for Mac OS X. But in 2004, it went cross-platform with releases for Windows, Linux (and Unix). And as of April 15, 2006 FrontBase is available for free, with no usage restrictions. You can purchase support services from them, however.

Currently at version 4.2.9, FrontBase has many features you’d associate with a professional database server, including:

  • SQL 92 support
  • Stored procedures
  • EncryptionREALbasic native plug-in
  • Terabyte databases
  • Backups
  • Indexing
  • Migration from MySQL and FileMaker

Installation

The FrontBase download is quite small (only 4.5MB for Windows, 14.6MB for OS X) and installation was straightforward and fast although I did get an error about a missing web component from the Windows installer. Even though FrontBase is free, you do have to go to the trouble of creating an account on the FrontBase web site to get a free license key. You have to request a separate key for each platform and also need to specify either the IP address or MAC address of the computer it will be installed on. Unless your server has a static IP address, it looks like the MAC address is the way to go. Of course obtaining your MAC address could be tricky. On Windows, type IPCONFIG /all and look for the line that says “Physical Address”. On Mac OS X, it is in your Network Preference panel. If you use Linux, I’m sure you can find it on your own.

Once you have this license you need to apply it to FrontBase by cutting and pasting it into a text file and putting this file in the FrontBase folder (\usr\FrontBase). Although this was not the most complicated database installation I’ve had to do, it certainly wasn’t the easiest either.

Database Administration

To access FrontBase, you use either the included SQL92 command line or the Java-based FrontBase JManager, but I had trouble getting that to connect (at least on Windows). The SQL92 command line gives you full control over the database server and the databases it is server, but you’ll obviously need to learn the commands (and there are plenty).

The JManager tool looks decent enough, although it suffers from its odd Java UI. They should really create a version of this in REALbasic.

Documentation

No documentation is installed to your machine, but you can download the 230 page user’s guide (in PDF format) from their web site. Since FrontBase uses SQL 92, you can find some books about that on Amazon. I didn’t find any FrontBase-specific books on Amazon, however. There also was not much information about FrontBase that I could find using Google.

Connecting to REALbasic

I created a sample database by starting the FrontBase SQL92 command line and entering these commands, one on each line:

create database firstdb;
connect to firstdb user _system;
create user test;
commit;
disconnect current;

This gives us a new database, called firstdb, with a user, called test. Now let’s see how easily we can connect to FrontBase using REALbasic. After downloading version 1.92 of the plugin (which, I’m am pleased to see, supports Mac OS X (including Universal Binaries), Windows and Linux), I copied it to the REALbasic plugins folder and started REALbasic (Professional 2008 Release 5). Keep in mind that in order to use databases besides REAL SQL Database, you need to have REALbasic Professional.

In a new blank project, add a PushButton to the default window and switch to its Action event. Add this code:

Dim firstDb As New FBDatabase
 
firstDb.Host = "localhost"
firstDb.DatabaseName = "firstdb"
firstDb.UserName = "test"
 
If firstDb.Connect Then
    MsgBox "Connected!"
Else
    MsgBox "Could not connect."
End If

Run the app and click the button. If everything is set up correctly, then you should get the “Connected!” message.

Now it works just like any other database. You can use firstDb.SQLSelect to process SELECT statements on database tables and you can use SQLExecute to run commands on the database.

Summary

If you can get past the slightly annoying installation, FrontBase seems like it would be worth a look. You’ll probably have to use the command-line, at least for some things, even if you can get the JManager tool to work. The only other database server that is also cross-platform, works with REALbasic and is completely free is PostgreSQL.

Current Notes 48

Software

REALbasic 2008 Release 5 – Now shipping. With tons of bug fixes and a few useful new features.

REAL Capture Canvas – Now available for free. Lets you capture video and audio using REALbasic

Formatted Text Control 1.2.1 – More updates to this powerful word processor control. And it’s on sale now for 33% off! FTC is also available at a 50% discount to ARBP members.

Spell Check Utilities 2.1 – A cross-platform spell checking plugin for REALbasic

Information

REAL Software updates web site – It sure is slick now. Create an account and you can easily access all your order history and download prior versions of REALbasic. The site is entirely powered by REAL SQL Server, but it uses PHP and not Yuma for the pages themselves.

Community

REAL World 2009 changes – REAL is instead planning to have smaller events in select cities around the U.S.

2008r5 Released! - Aaron gives some background on the latest release

Optional Parameters and Interfaces – Aaron explains how these features of REALbasic work

Touchy Subject - More about the way REALbasic now builds Windows apps

The Trick to Bug Reports – Advice on how to write a good bug report

REAL World 2009 Cancelled – Thoughts on the conference changes