💾 Database
The Database entity provides programmers a way to access SQL databases easily through scripting.
💂Authority
This class can only be spawned on 🟦 Server side.
🧑💻API Source
This page is auto-generated! The Functions, Properties and Events described here are defined in our GitHub's API Repository! Feel free to commit suggestions and changes to the source .json API files!
tip
Currently nanos world supports SQLite
, MySQL
and PostgreSQL
out of the box.
🎒 Examples
Server/Index.lua
-- Creates a SQLite connection, using a local file called 'database_filename.db'
local sqlite_db = Database(DatabaseEngine.SQLite, "db=database_filename.db timeout=2")
-- Creates a table
sqlite_db:Execute([[
CREATE TABLE IF NOT EXISTS test (
id INTEGER,
name VARCHAR(100)
)
]])
-- Insert values in the table
local affected_rows = sqlite_db:Execute("INSERT INTO test VALUES (1, 'amazing')")
Console.Log("Affected Rows: " .. tostring(affected_rows))
-- Will output: 1
-- Selects the data
local rows = sqlite_db:Select("SELECT * FROM test")
Console.Log(NanosTable.Dump(rows))
-- Will output a table with all data from 'test'
-- Selects the data with filter
local rows_filter = sqlite_db:Select("SELECT * FROM test WHERE name = :0", "amazing")
Console.Log(NanosTable.Dump(rows_filter))
-- Will output a table with all data from 'test' where name matches 'amazing'
(Database.Execute) Inserts into database (SQLite)
local affected_rows = my_database:Execute("INSERT INTO MyTable VALUES (:0, ':1')", 123, "MyValue")
(Database.Select) Selects from a table (SQLite)
local rows = my_database:Select("SELECT * FROM MyTable WHERE name = :0 AND title = :1", "Val", "AnotherVal")
(Database.SelectAsync) Selects from a table asynchronously (SQLite)
my_database:SelectAsync("SELECT * FROM MyTable WHERE name = :0 AND title = :1", function(rows)
Console.log(NanosTable.Dump(rows))
end, "Val", "AnotherVal")
tip
All requests are thread safe! 🥳
🛠 Constructors
Default Constructor
local my_database = Database(database_engine, connection_string, pool_size?)
Type | Name | Default | Description |
---|---|---|---|
DatabaseEngine | database_engine | Required parameter | Database Engine |
string | connection_string | Required parameter | Connection String used to create and connect to the database |
integer | pool_size | 10 | Size of the connection pool when calling several queries simultaneously |
note
The initial connection to the Database (when it's being constructed) is made on the main thread, so expect the server hanging for a few seconds during that.
info
If the Database fails to connect, it will spit an error on console and will return nil
.