W3cubDocs

/Nim

Module db_odbc

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:

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

Examples

Opening a connection to a database

import db_odbc
var db = open("localhost", "user", "password", "dbname")
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, ?)",
        "Andreas")

Large example

import db_odbc, math

var theDb = open("localhost", "nim", "nim", "test")

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

theDb.exec(sql"START TRANSACTION")
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, odbcsql, db_common

Types

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

Procs

proc dbError(db: var DbConn) {...}{.tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].}
Raises an [DbError] exception with ODBC error information
proc dbQuote(s: string): string {...}{.noSideEffect, raises: [], tags: [].}
DB quotes the string.
proc tryExec(db: var 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: var DbConn; query: SqlQuery; args: varargs[string, `$`]) {...}{.
    tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].}
Executes the query and raises EDB if not successful.
proc `[]`(row: InstantRow; col: int): string {...}{.inline, raises: [], tags: [].}
Returns text for given column of the row
proc len(row: InstantRow): int {...}{.inline, raises: [], tags: [].}
Returns number of columns in the row
proc getRow(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{.
    tags: [ReadDbEffect, WriteDbEffect], 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: var DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[Row] {...}{.
    tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].}
Executes the query and returns the whole result dataset.
proc getValue(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): string {...}{.
    tags: [ReadDbEffect, WriteDbEffect], raises: [].}
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: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{.
    tags: [ReadDbEffect, 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: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{.
    tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].}
Executes the query (typically "INSERT") and returns the generated ID for the row.
proc execAffectedRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{.
    tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].}
Runs the query (typically "UPDATE") and returns the number of affected rows
proc close(db: var DbConn) {...}{.tags: [WriteDbEffect], raises: [].}
Closes the database connection.
proc open(connection, user, password, database: string): DbConn {...}{.
    tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].}

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.

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

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

Iterators

iterator fastRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{.
    tags: [ReadDbEffect, WriteDbEffect], 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 may cause a driver error for subsequenct queries

Rows are retrieved from the server at each iteration.

iterator instantRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {...}{.
    tags: [ReadDbEffect, WriteDbEffect], 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 interator body.
iterator rows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{.
    tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].}

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.

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