Prepares (compiles) an SQL statement, ready to be executed with DatabaseStep.
You need to supply the database id of an existing opened database, and the SQL statement to be executed. Only one statement should be supplied. If multiple statements are supplied, only the first will be used. (eg. "drop table a; drop table b" - in this case only the first "drop table" would be executed).
If there is a syntax error in your SQL, that will be reported by a non-zero return code from DatabasePrepare. The most recent error message string (if any) can be obtained by calling DatabaseError.
Note that to include single quotes inside a string literal, in your SQL statement they must be doubled. For example:
INSERT INTO weapons (name, damage) VALUES ('Nick''s sword', 42)
Only one statement can be active at once, so after doing a DatabasePrepare you must do DatabaseFinalize before doing another DatabasePrepare. The exception is that if DatabasePrepare returns an error, then you do not need to do DatabaseFinalize because there is no active statement.
After successfully doing DatabasePrepare, you then need to call DatabaseStep for each row in the query. This is the execution phase. For SQL statements that return multiple rows of data, you need to do DatabaseStep once for each row. For SQL statements that just do one thing (like INSERT INTO) then you only need to call DatabaseStep once.
Also see DatabaseExec if you only need to execute SQL statements (like INSERT INTO) which do not return any results.
Note: Available in version 4.40 onwards.
Lua example
-- insert a record
DatabasePrepare ("db", "INSERT INTO weapons (name, damage) VALUES ('sword', 42)") --> returns 0 (sqlite3.OK)
DatabaseStep ("db") -- returns 101 (sqlite3.DONE)
DatabaseFinalize ("db") -- returns 0 (sqlite3.OK)
-- see the DatabaseStep entry for a more elaborate example.
-- A suitable function for fixing up strings is this:
-- Quote the argument, replacing single quotes with two lots of single quotes.
-- If nil supplied, return NULL (not quoted).
function fixsql (s)
if s then
return "'" .. (string.gsub (s, "'", "''")) .. "'"
else
return "NULL"
end -- if
end -- fixsql