Note: In order to use this module, run nimble install db_connector.

A higher level ODBC database wrapper.

This is the same interface that is implemented for other databases.

This has NOT yet been (extensively) tested against ODBC drivers for Teradata, Oracle, Sybase, MSSqlvSvr, et. al. databases.

Currently all queries are ANSI calls, not Unicode.

See also: db_postgres, db_sqlite, 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:

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

Examples

Opening a connection to a database

  1. import db_connector/db_odbc
  2. var db = open("localhost", "user", "password", "dbname")
  3. db.close()

Creating a table

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

Inserting data

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

Large example

  1. import db_connector/db_odbc
  2. import std/math
  3. var theDb = open("localhost", "nim", "nim", "test")
  4. theDb.exec(sql"Drop table if exists myTestTbl")
  5. theDb.exec(sql("create table myTestTbl (" &
  6. " Id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, " &
  7. " Name VARCHAR(50) NOT NULL, " &
  8. " i INT(11), " &
  9. " f DECIMAL(18,10))"))
  10. theDb.exec(sql"START TRANSACTION")
  11. for i in 1..1000:
  12. theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
  13. "Item#" & $i, i, sqrt(i.float))
  14. theDb.exec(sql"COMMIT")
  15. for x in theDb.fastRows(sql"select * from myTestTbl"):
  16. echo x
  17. let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
  18. "Item#1001", 1001, sqrt(1001.0))
  19. echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
  20. theDb.close()

Imports

odbcsql, db_common, dbutils

Types

  1. DbConn = OdbcConnTyp

encapsulates a database connection

  1. InstantRow = tuple[row: seq[string], len: int]

a handle that can be used to get a row’s column text on demand

  1. Row = seq[string]

a row of a dataset. NULL database values will be converted to nil.

Procs

  1. proc `[]`(row: InstantRow; col: int): string {.inline, ...raises: [], tags: [],
  2. forbids: [].}

Returns text for given column of the row

  1. proc close(db: var DbConn) {....tags: [WriteDbEffect], raises: [], forbids: [].}

Closes the database connection.

  1. proc dbError(db: var DbConn) {....tags: [ReadDbEffect, WriteDbEffect],
  2. raises: [DbError], forbids: [].}

Raises an [DbError] exception with ODBC error information

  1. proc dbQuote(s: string): string {.noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

DB quotes the string.

  1. proc exec(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]) {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

Executes the query and raises EDB if not successful.

  1. proc execAffectedRows(db: var DbConn; query: SqlQuery;
  2. args: varargs[string, `$`]): int64 {.
  3. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

Runs the query (typically “UPDATE”) and returns the number of affected rows

  1. proc getAllRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[
  2. Row] {....tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

Executes the query and returns the whole result dataset.

  1. proc getRow(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

Retrieves a single row. If the query doesn’t return any rows, this proc will return a Row with empty strings for each column.

  1. proc getValue(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): string {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}

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.

  1. proc insert(db: var DbConn; query: SqlQuery; pkName: string;
  2. args: varargs[string, `$`]): int64 {.
  3. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

same as insertId

  1. proc insertId(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

Executes the query (typically “INSERT”) and returns the generated ID for the row.

  1. proc len(row: InstantRow): int {.inline, ...raises: [], tags: [], forbids: [].}

Returns number of columns in the row

  1. proc open(connection, user, password, database: string): DbConn {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

Opens a database connection.

Raises EDb if the connection could not be established.

Currently the database parameter is ignored, but included to match open() in the other db_xxxxx library modules.

  1. proc setEncoding(connection: DbConn; encoding: string): bool {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

Currently not implemented for ODBC.

Sets the encoding of a database connection, returns true for success, false for failure. result = set_character_set(connection, encoding) == 0

  1. proc tryExec(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}

Tries to execute the query and returns true if successful, false otherwise.

  1. proc tryInsert(db: var DbConn; query: SqlQuery; pkName: string;
  2. args: varargs[string, `$`]): int64 {.
  3. ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}

same as tryInsertID

  1. proc tryInsertId(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}

Executes the query (typically “INSERT”) and returns the generated ID for the row or -1 in case of an error.

  1. proc unsafeColumnAt(row: InstantRow; index: int): cstring {.inline, ...raises: [],
  2. tags: [], forbids: [].}

Return cstring of given column of the row

Iterators

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

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 may cause a driver error for subsequent queries

Rows are retrieved from the server at each iteration.

  1. iterator instantRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

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.

  1. iterator rows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

Same as fastRows, but slower and safe.

This retrieves ALL rows into memory before iterating through the rows. Large dataset queries will impact on memory usage.

Exports

DbTypeKind, sql, DbType, SqlQuery, DbColumn, ReadDbEffect, DbError, WriteDbEffect, dbError, DbColumns, DbEffect