db:prepare

Compiles an SQL statement

Prototype

db:prepare(sql)

Description

This function compiles the SQL statement in string sql into an internal representation and returns this as userdata. The returned object should be used for all further method calls in connection with this specific SQL statement.

CALLBACK CONTEXTS

A callback context is available as a parameter inside the callback functions db:create_aggregate(), db:create_function() and db:prepare(). It can be used to get further information about the state of a query.

The various context functions are:

context:aggregate_count
context:get_aggregate_data
context:result
context:result_blob
context:result_error
context:result_int
context:result_null
context:result_number
context:result_text
context:set_aggregate_data
context:user_data

Example

require "tprint"

-- make in-memory database
db = sqlite3.open_memory()

-- make a table for testing
db:exec  [[
          CREATE TABLE mobs (name, class, hp);
          INSERT INTO mobs VALUES("Naga", "mage", 666);
          INSERT INTO mobs VALUES("Wolf", "beast", 42);
          INSERT INTO mobs VALUES("Guard", "warrior", 100);
       ]]

-- prepare a SELECT statement
local stmt = db:prepare ("SELECT * FROM mobs")

-- loop until we get everything
while true do

  local result = stmt:step ()

  -- exit loop if done
  if result == sqlite3.DONE then
    break
  end -- if done

  -- should have ROW result
  assert (result == sqlite3.ROW, "Row not found")

  -- get all values into a table
  local row = stmt:get_named_values ()

  -- display them
  print (string.rep ("-", 20))
  tprint (row)
  
end -- while

-- done with this statement
stmt:finalize ()

-- finished with database
db:close ()

Lua functions

Topics