W3cubDocs

/Nim

Module db_sqlite

A higher level SQLite database wrapper. This interface is implemented for other databases too.

See also: db_odbc, db_postgres, db_mysql.

Parameter substitution

All db_* modules support the same form of parameter substitution. That is, using the ? (question mark) to signify the place where a value should be placed. For example:

sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"

Examples

Opening a connection to a database

import db_sqlite
let db = open("mytest.db", nil, nil, nil)  # user, password, database name can be nil
db.close()

Creating a table

db.exec(sql"DROP TABLE IF EXISTS myTable")
db.exec(sql("""CREATE TABLE myTable (
                 id integer,
                 name varchar(50) not null)"""))

Inserting data

db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
        "Jack")

Larger example

import db_sqlite, math

let theDb = open("mytest.db", "", "", "")

theDb.exec(sql"Drop table if exists myTestTbl")
theDb.exec(sql("""create table myTestTbl (
     Id    INTEGER PRIMARY KEY,
     Name  VARCHAR(50) NOT NULL,
     i     INT(11),
     f     DECIMAL(18,10))"""))

theDb.exec(sql"BEGIN")
for i in 1..1000:
  theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
        "Item#" & $i, i, sqrt(i.float))
theDb.exec(sql"COMMIT")

for x in theDb.fastRows(sql"select * from myTestTbl"):
  echo x

let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
      "Item#1001", 1001, sqrt(1001.0))
echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)

theDb.close()

Exports

dbSerial, dbUser5, dbLine, dbBool, DbTypeKind, dbUInt, dbGeometry, dbInet, dbUser4, sql, dbUser3, dbPolygon, DbType, dbSet, dbFloat, dbMacAddress, dbVarchar, dbBit, dbArray, dbUser1, dbLseg, SqlQuery, db_common, DbColumn, dbBox, ReadDbEffect, dbNull, DbError, dbDate, dbUuid, dbJson, dbUrl, dbDecimal, dbXml, dbUnknown, WriteDbEffect, dbBlob, dbEnum, dbError, dbTime, DbColumns, dbPoint, DbEffect, dbTimeInterval, dbPath, dbTimestamp, dbCircle, dbInt, dbDatetime, dbComposite, dbFixedChar, dbUser2

Imports

strutils, sqlite3, db_common

Types

DbConn = PSqlite3
encapsulates a database connection
Row = seq[string]
a row of a dataset. NULL database values will be converted to nil.
InstantRow = Pstmt
a handle that can be used to get a row's column text on demand

Procs

proc dbError(db: DbConn) {...}{.noreturn, raises: [DbError], tags: [].}
raises a DbError exception.
proc dbQuote(s: string): string {...}{.raises: [], tags: [].}
DB quotes the string.
proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {...}{.
    tags: [ReadDbEffect, WriteDbEffect], raises: [].}
tries to execute the query and returns true if successful, false otherwise.
proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) {...}{.
    tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].}
executes the query and raises DbError if not successful.
proc `[]`(row: InstantRow; col: int32): string {...}{.inline, raises: [], tags: [].}
returns text for given column of the row
proc len(row: InstantRow): int32 {...}{.inline, raises: [], tags: [].}
returns number of columns in the row
proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{.
    tags: [ReadDbEffect], raises: [DbError].}
retrieves a single row. If the query doesn't return any rows, this proc will return a Row with empty strings for each column.
proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[Row] {...}{.
    tags: [ReadDbEffect], raises: [DbError].}
executes the query and returns the whole result dataset.
proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string {...}{.
    tags: [ReadDbEffect], raises: [DbError].}
executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL.
proc tryInsertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{.
    tags: [WriteDbEffect], raises: [].}
executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error.
proc insertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{.
    tags: [WriteDbEffect], raises: [DbError].}
executes the query (typically "INSERT") and returns the generated ID for the row. For Postgre this adds RETURNING id to the query, so it only works if your primary key is named id.
proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{.
    tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].}
executes the query (typically "UPDATE") and returns the number of affected rows.
proc close(db: DbConn) {...}{.tags: [DbEffect], raises: [DbError].}
closes the database connection.
proc open(connection, user, password, database: string): DbConn {...}{.tags: [DbEffect],
    raises: [DbError].}
opens a database connection. Raises EDb if the connection could not be established. Only the connection parameter is used for sqlite.
proc setEncoding(connection: DbConn; encoding: string): bool {...}{.tags: [DbEffect],
    raises: [DbError].}

sets the encoding of a database connection, returns true for success, false for failure.

Note that the encoding cannot be changed once it's been set. According to SQLite3 documentation, any attempt to change the encoding after the database is created will be silently ignored.

Iterators

iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{.
    tags: [ReadDbEffect], raises: [DbError].}

Executes the query and iterates over the result dataset.

This is very fast, but potentially dangerous. Use this iterator only if you require ALL the rows.

Breaking the fastRows() iterator during a loop will cause the next database query to raise a DbError exception unable to close due to ....

iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {...}{.
    tags: [ReadDbEffect], raises: [DbError].}
same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within the iterator body.
iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery;
                    args: varargs[string, `$`]): InstantRow {...}{.tags: [ReadDbEffect],
    raises: [DbError].}
same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within the iterator body.
iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{.
    tags: [ReadDbEffect], raises: [DbError].}
same as FastRows, but slower and safe.

© 2006–2018 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/db_sqlite.html