FiveM Database Access in Lua: Safe, Fast Queries with oxmysql


Most FiveM scripts that lag a server or leak money do it at the database layer: a query inside a loop, a string-concatenated WHERE clause, or a save on every single item move. This article covers how to structure database access in a Lua resource so it stays safe under abuse and cheap under load. The examples use oxmysql, which QBCore, ESX and Qbox all build on.
The database belongs to the server
Database calls only ever run in server scripts. That part is obvious, but the mistake that follows is less obvious: writing a generic server event that the client can use to trigger a query with its own values. If a client can send a table name, a column, an amount or an identifier and the server writes it, a cheater can write it too.
The rule is simple. The client sends intent ("I want to buy item X"), the server looks up who the player is from source, checks the price and the balance itself, and only then touches the database. The player identifier is always resolved server-side, never taken from event arguments.
Setting up oxmysql in a resource
Load the oxmysql library file before your own server scripts and declare the dependency so the resource does not start before the database is ready.
fx_version 'cerulean'
game 'gta5'
lua54 'yes'
server_scripts {
'@oxmysql/lib/MySQL.lua',
'server/main.lua'
}
dependency 'oxmysql'This gives you the global MySQL object in your server files. The connection string itself lives in server.cfg, not in your resource, so you never ship credentials inside a script.
Always use parameters
Never build SQL by concatenating strings, even for values you think are safe. Player names, plate text and item metadata can all contain quotes.
-- Wrong: injectable
local row = MySQL.single.await("SELECT * FROM vehicles WHERE plate = '" .. plate .. "'")
-- Right: parameterized
local row = MySQL.single.await('SELECT * FROM vehicles WHERE plate = ?', { plate })Parameters also let the driver reuse query plans, so they are faster as well as safer. Note that parameters only work for values. Table and column names cannot be parameters, so if you ever need dynamic columns, map them from a fixed whitelist in your code rather than accepting a string from anywhere.
Pick the right helper
oxmysql exposes several helpers. Using the specific one keeps your code readable and avoids unpacking result tables by hand.
MySQL.queryreturns all matching rows as a list.MySQL.singlereturns the first row ornil.MySQL.scalarreturns the first column of the first row, useful for counts and single values.MySQL.insertreturns the inserted id.MySQL.updatereturns the number of affected rows.MySQL.prepareruns a prepared statement and is a good fit for queries you execute very often.
Each one has an .await variant that returns the result directly, and a callback form. Check MySQL.update results: if you expected one row to change and got zero, something is wrong and you should not continue as if the write succeeded.
Await versus callbacks
The .await variants yield the current coroutine until the query finishes. That works inside event handlers and inside threads created with CreateThread. At the top level of a file, wrap the call in a thread.
Await reads top to bottom and makes error handling straightforward, which is why most modern scripts use it. Callbacks still have a place for fire-and-forget writes such as logs, where you do not need the result and do not want to hold up the handler.
-- Fire and forget: nothing waits on this
MySQL.insert('INSERT INTO shop_logs (identifier, item, amount) VALUES (?, ?, ?)', { identifier, item, amount })Cache hot data, write when it matters
The biggest performance win is not querying at all. Data that is read constantly, such as a player's owned items in your script or their unlocked perks, should be loaded once and kept in a Lua table keyed by identifier or server id.
local cache = {}
local function getIdentifier(src)
return GetPlayerIdentifierByType(src, 'license')
end
local function loadPlayer(src)
local identifier = getIdentifier(src)
if not identifier then return end
local row = MySQL.single.await('SELECT data FROM my_progress WHERE identifier = ?', { identifier })
cache[src] = {
identifier = identifier,
data = row and json.decode(row.data) or {},
dirty = false
}
end
local function savePlayer(src)
local entry = cache[src]
if not entry or not entry.dirty then return end
MySQL.update.await(
'INSERT INTO my_progress (identifier, data) VALUES (?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data)',
{ entry.identifier, json.encode(entry.data) }
)
entry.dirty = false
end
AddEventHandler('playerDropped', function()
local src = source
savePlayer(src)
cache[src] = nil
end)
CreateThread(function()
while true do
Wait(5 * 60 * 1000)
for src in pairs(cache) do
savePlayer(src)
end
end
end)The dirty flag means you only write players whose data actually changed. The periodic flush limits how much progress a crash can cost. In a framework, call loadPlayer from the framework's own "player loaded" server event instead of inventing your own trigger.
Do not cache everything. Money and anything shared between players (a business stash, a jointly owned house) should be read and written with the database as the source of truth, or handled by the framework that already owns it.
Use transactions for multi-step changes
Any operation that changes two rows that must stay consistent belongs in a transaction. A classic example is transferring stock between two storages: if the server dies between the two updates, items either vanish or duplicate.
local ok = MySQL.transaction.await({
{ query = 'UPDATE storages SET amount = amount - ? WHERE id = ? AND amount >= ?', values = { qty, fromId, qty } },
{ query = 'UPDATE storages SET amount = amount + ? WHERE id = ?', values = { qty, toId } }
})
if not ok then
-- nothing was applied, tell the player and stop
endNotice the amount >= ? guard in the first statement. Pushing the balance check into the SQL itself protects you against two requests arriving at the same moment, which a Lua-side check alone cannot fully prevent. One caveat: an UPDATE that matches no rows is not an error, so the transaction does not fail on its own when the stock is too low. Read the stock first inside your own checks, or run the guarded decrement by itself, confirm it changed exactly one row, and only then apply the other side.
Schema habits that save you later
- Index what you filter on. If every lookup is
WHERE identifier = ?orWHERE plate = ?, that column needs an index or a primary/unique key. Without one, every query scans the whole table, and that gets worse every week the server runs. - Use a unique key for upserts.
ON DUPLICATE KEY UPDATEonly works if the identifier column is unique. - Use proper types. Integers for amounts, not strings. Store structured blobs as JSON only when you never need to query inside them.
- Ship a SQL file. Include an install script with
CREATE TABLE IF NOT EXISTSso server owners are not guessing at column types. - Prefix your tables. Names like
myres_progressavoid collisions with other resources.
Finding slow queries
If resmon shows your resource spiking on the server side, look for queries in loops first: a for over players that runs one SELECT each should usually become one query with IN (...) or a cached lookup. oxmysql can also warn about slow queries in the server console; its documentation lists the setting. When a specific query is slow, run it with EXPLAIN in your database client to see whether it uses an index.
For native functions such as identifier lookups, the reference at docs.fivem.net/natives is the place to confirm names and return values before relying on them.
Takeaway
- Run SQL only on the server and resolve the player from
source, never from event arguments. - Use parameters for every value; whitelist anything structural.
- Pick the specific helper and check affected rows on writes.
- Cache per-player data, track a dirty flag, save on drop and on a timer.
- Wrap multi-row changes in transactions and put balance guards in the SQL.
- Index every column you filter on and ship a clean install file.