Why Is My Recordset Nil?

This one comes up on the RB Forums a lot.  The post generally goes something like this:  “I have a database and everything works fine until here <insert code snippet> and I get a Nil Object Exception because rs is nil.”

If everything else is working fine then it must be the recordset.  If you’re not checking the database for an error you’ll never know!  The db.error property tells you that you had an error and the db.errormessage property does a pretty good job of telling you what the error is.

dim rs as recordset
rs = db.SQLSelect(“SELECT * FROM sometable WHERE somefield=avalue”)
if db.error then
msgbox “Error!” + db.ErrorMessage

//do something with the recordset here.

I find this happens a lot with developers that came from Visual Basic 6 where database errors throw an exception.  REALbasic doesn’t work the same way.  Get over it and start checking for database errors.

If you want to capture database errors you can do something like what we’ve done:

if gDB.Error then Raise new BK_Debug.BK_DatabaseException(gDB.ErrorMessage, s)

Where BK_DatabaseException is a RuntimeException subclass defined like this:

Sub Constructor(sMessage as string, sSQL as string)
If sMessage <> “” Then
Me.Message = sMessage
End If

If sSQL <> “” Then
Me.Message = Me.Message + EndOfLine +  EndOfLine + sSQL
End Sub

This can be useful if you have automated error handling and can receive this information.  Of course, if you’re creating a runtime exception you had better be handling them in the app.unhandledexception event otherwise your app will shutdown and you’ll have pissed off users.