[ library(dbi) | Reference Manual | Alphabetic Index ]

session_sql_prepare(++Session, +ParamTemplate, ++SQL, -Cursor)

Prepares a non-query SQL statement for execution by the DBMS.
A session handle
Template defining the types of the parameters (structure or [])
A SQL statement in prepared syntax (string)
Returned cursor handle


Prepares a non-query SQL statement for execution. The statement is not actually executed, and a cursor_*_execute family of predicate is required to execute the predicate. This facility is only available if the DBMS supports prepared statements, and the SQL statement has to be written in the prepared statement syntax of the DBMS. The predicate returns the cursor handle representing this prepared statement in Cursor, which can then be used in subsequent library predicates.

The SQL statement must be a non-query, i.e. it does not return any results. If the SQL statement is a query, a dbi_bad_query error would be raise if the DBMS can detect the error during preparation, otherwise an error would be raised when the statement is executed

A prepared SQL statement is parsed by the DBMS, so that it could be executed more efficiently. It can also be parameterised, where the parameters represent values to be filled in when the statement is executed. The statement can be executed multiple times with different parameters. The types of the parameters is specified by ParamTemplate, which is a Prolog structure of arity M (where M is the number of parameters for the statement), or the nil atom [] if there are no parameters. See the general description of this library or the manual for a description of the template specification.

The SQL statement must be valid for the DBMS to execute. It can contain NULL characters, i.e. it can contain binary data. The SQL statement cannot return any results, i.e. it should not be a query. If it does, then an error would be raised when the SQL statement is actually executed. The error is not detected at this predicate because the database cannot tell if a SQL statement will return results or not until it is executed.

Note that some DBMS restricts which SQL statements can be prepared. If an SQL statement cannot be prepared, it can still be executed using session_sql/3.


(5) type error
Session is not a valid session handle, or SQL not a string, or ParamTemplate not a structure
Error from DBMS while preparing SQL
ParamTemplate has the wrong arity
SQL is a query


  % note '?' in SQL in the syntax MySQL uses for placeholders. This may be
  % different in other DBMS
  transfer_(Session, Amount, FromAccount, ToAccount) :-
      SQL = "update accounts set balance = balance + ? \
                                               where id = ?",
      Deduct is - Amount,
      % incbal(1.0,12) is the parameter template

See Also

cursor_next_execute / 2, cursor_all_execute / 2, cursor_N_execute / 4, cursor_close / 1, session_sql / 3, session_sql_prepare_query / 5