Skip to main content

Database and SQL

BBj accesses databases through a family of SQL verbs: SQLOPEN opens a connection, SQLPREP prepares a statement, SQLEXEC executes it, and SQLFETCH retrieves results row by row. This chapter uses the ChileCompany sample database that ships with every BBj installation -- no setup required.

At a Glance

Verb/FunctionSyntaxPurpose
SQLOPENSQLOPEN(chan)"dbname"Open database connection
SQLPREPSQLPREP(chan)"sql$"Prepare SQL statement
SQLTMPLDIM rec$:SQLTMPL(chan)Get result template for field access
SQLEXECSQLEXEC(chan)argsExecute prepared statement
SQLFETCHrec$=SQLFETCH(chan,END=done)Fetch next result row
SQLCLOSESQLCLOSE(chan)Close connection
SQLERRSQLERR(chan)Get last SQL error text

For Java, Python, and C# Developers

TaskJavaPythonC#BBj
Open connectionDriverManager.getConnection()sqlite3.connect()SqlConnection.Open()SQLOPEN(chan) "DbName"
Prepare queryconn.prepareStatement(sql)cursor.execute(sql, params)new SqlCommand(sql)SQLPREP(chan) sql$
Execute querystmt.executeQuery()cursor.execute(sql)cmd.ExecuteReader()SQLEXEC(chan) args
Fetch rowrs.next(); rs.getString()cursor.fetchone()reader.Read()rec$ = SQLFETCH(chan, END=done)
Close connectionconn.close()conn.close()conn.Close()SQLCLOSE(chan)
Get errore.getMessage()e.args[0]e.MessageSQLERR(chan)

BBj SQL uses verbs (SQLOPEN, SQLPREP, SQLEXEC, SQLFETCH) rather than objects. Parameters use ? placeholders and are passed as arguments to SQLEXEC. For the complete cross-language reference, see BBj for Java, Python, and C# Developers.

Complete Runnable Examples

This chapter's code snippets illustrate individual concepts. For complete, runnable programs you can open directly in the BBj IDE, see the sample files in samples/08-database-sql/:

  • sqlopen_basic.bbj -- Basic SQL connection with SQLOPEN and SQLFETCH
  • select_query.bbj -- Parameterized SELECT with SQLPREP and SQLEXEC
  • insert_update.bbj -- INSERT, UPDATE, and DELETE operations
  • sql_patterns.bbj -- SQL error handling with SETERR and SQLERR

See Running Samples for setup instructions.