The DB table lets scripts run SQL statements on the GameServer's database. Both functions run the statement asynchronously (on the database thread), so the script does not stall waiting; the result of DB.Query is returned later through the onDBQueryResult callback (callback module CallbacksDB.lua).

Every string coming from players or from an untrusted source, when put into an SQL statement, must go through DB.Escape to prevent SQL injection attacks. The DB.Query and DB.Execute functions execute the SQL statement you give them verbatim.

DB.Query

Sends a SELECT query that runs in the background. The result is returned through the onDBQueryResult callback together with the exact label and param you passed, so you can recognize it.

DB.Query(sql, label, param) -> integer
ParameterTypeDescription
sqlstringThe SQL query
labelstringA label to tell the queries apart when receiving results (usually the name of the handler function)
paramstringAn accompanying parameter string (for example the index and ID of the character), returned verbatim with the result

Returns: 1 if the query was sent; 0 if sql is empty. Short name: SQLAsyncQuery.

By the time the result arrives, the player may have left or the aIndex may already be used by someone else. Put both aIndex and Player.GetCharacterID(aIndex) into param and check them again before acting on the character.

The callback receives (label, param, result); result is a table of rows, or the number 0 when there are no rows / the query failed. At most 10000 rows are returned to Lua: extra rows are dropped and GameServer writes a warning to the log. Details (column types, the return value for re-running the query) are on the page Asynchronous DB queries.

local acc = DB.Escape(Player.GetAccount(aIndex))
DB.Query(string.format("SELECT Tier FROM MyRewards WHERE Account = '%s'", acc),
    "MyRewards_Result", string.format("%d:%d", aIndex, Player.GetCharacterID(aIndex)))

DB.Execute

Runs an INSERT / UPDATE / DELETE statement in the background, with no result returned.

DB.Execute(sql)
ParameterTypeDescription
sqlstringThe SQL statement. An empty string does nothing

Returns: no return value. The function puts the statement in a queue and returns immediately; there is no way to know whether the statement succeeded.

DB.Execute(string.format("UPDATE MyRewards SET LastClaim = %d WHERE Account = '%s'",
    os.time(), DB.Escape(Player.GetAccount(aIndex))))

DB.Escape

Escapes the special characters of a string so it can be put safely inside the single quotes '...' of an SQL statement.

DB.Escape(text) -> string
ParameterTypeDescription
textstringThe string to escape (a number is converted to a string)

Returns: the escaped string; an empty string if text is not a string / number.

local name = DB.Escape(Player.GetName(aIndex))
local sql = "SELECT * FROM Logs WHERE Name = '" .. name .. "'"