Sqlitex.Statement
Provides an interface for working with sqlite prepared statements.
Care should be taken when using prepared statements directly - they are not immutable objects like most things in Elixir. Sharing a statement between different processes can cause problems if the processes accidentally interleave operations on the statement. It’s a good idea to create different statements per process, or to wrap the statements up in a GenServer to prevent interleaving operations.
Example
iex(2)> {:ok, db} = Sqlitex.open(":memory:")
iex(3)> Sqlitex.query(db, "CREATE TABLE data (id, name);")
[]
iex(6)> {:ok, statement} = Sqlitex.Statement.prepare(db, "INSERT INTO data VALUES (?, ?);")
iex(7)> Sqlitex.Statement.bind_values(statement, [1, "hello"])
iex(8)> Sqlitex.Statement.exec(statement)
:ok
iex(9)> {:ok, statement} = Sqlitex.Statement.prepare(db, "SELECT * FROM data;")
iex(10)> Sqlitex.Statement.fetch_all(statement)
[[id: 1, name: "hello"]]
iex(11)> Sqlitex.close(db)
:ok
Summary↑
| bind_values!(statement, values) | Same as |
| bind_values(statement, values) | Binds values to a Sqlitex.Statement |
| exec!(statement) | Same as |
| exec(statement) | Runs a statement that returns no results |
| fetch_all!(statement, into \\ []) | Same as |
| fetch_all(statement, into \\ []) | Fetches all rows using a statement |
| prepare!(db, sql) | Same as |
| prepare(db, sql) | Prepare a Sqlitex.Statement |
| time_to_string(arg1) |
Functions
Binds values to a Sqlitex.Statement
Parameters
statement- The statement to bind values into.values- A list of values to bind into the statement.
Returns
{:ok, statement}on success- See
:esqlite3.preparefor errors.
Value transformations
Some values will be transformed before insertion into the database.
nil- Converted to :undefinedtrue- Converted to 1false- Converted to 0datetime- Converted into a string. See datetime_to_string%Decimal- Converted into a number.
Same as bind_values/2 but raises a Sqlitex.Statement.BindValuesError on error.
Returns the statement otherwise.
Runs a statement that returns no results.
Should be called after the statement has been bound.
Parameters
statement- The statement to run.
Returns
:ok{:error, error}
Same as exec/1 but raises a Sqlitex.Statement.ExecError on error.
Returns :ok otherwise.
Fetches all rows using a statement.
Should be called after the statement has been bound.
Parameters
statement- The statement to run.into- The collection to put the results into. Defaults to an empty list.
Returns
{:ok, results}{:error, error}
Same as fetch_all/2 but raises a Sqlitex.Statement.FetchAllError on error.
Returns the results otherwise.
Prepare a Sqlitex.Statement
Parameters
db- The database to prepare the statement for.sql- The SQL of the statement to prepare.
Returns
{:ok, statement}on success- See
:esqlite3.preparefor errors.
Same as prepare/2 but raises a Sqlitex.Statement.PrepareError on error.
Returns a new statement otherwise.