Mt4-sqlite

From Shmuma

Jump to: navigation, search


Some time ago, I needed a fast and small storage for MetaTrader4 experts. CSV files are slow, binary files are ugly, so I decided to create SQLite wrapper dll for MT4.

Project GIT repository: http://github.com/Shmuma/sqlite3-mt4-wrapper

Contents

Change history

  • 2011-04: fixed bug with db create erron on W7/Vista. Now DBs created in ~/Application Data/MT-Sqlite.
  • 2010-07: fixed bug with relative pathnames
  • 2009-10: first public release

Download

Installation

  1. Download it,
  2. copy sqlite3_wrapper.dll into system32 folder (or anywhere MT can find it),
  3. copy sqlite.mqh into includes folder.

Usage

There are two examples which perform schema creation, data insertion and query.

Library exports six routines:

  1. int sqlite_exec (string db, string sql) — executes query which result we are not interested in (for example, create, update or delete). If database doesn't exist, it will be created. Path to database can be absolute or relative to the current path of program.
  2. int sqlite_table_exists (string db, string table) — returns 1 if table exists, 0 if not.
  3. int sqlite_query (string db, string sql, int& cols[]) — performs query and returns integer handle to query results. To iterate over data, use sqlite_next_row and sqlite_get_col. To free results, use sqlite_free_query.
  4. int sqlite_next_row (int handle) — fetches next row into internal space.
  5. string sqlite_get_col (int handle, int col) — obtains column's value.
  6. int sqlite_free_query (int handle) — frees query handle.

Examples

#include "sqlite.mqh"

bool do_check_table_exists (string db, string table)
{
    int res = sqlite_table_exists (db, table);

    if (res < 0) {
        Print ("Check for table existence failed with code " + res);
        return (false);
    }

    return (res > 0);
}

void do_exec (string db, string exp)
{
    int res = sqlite_exec (db, exp);
    
    if (res != 0)
        Print ("Expression '" + exp + "' failed with code " + res);
}

int start ()
{
    string db = "test.db";

    if (!do_check_table_exists (db, "test")) {
        Print ("DB not exists, create schema");
        do_exec (db, "create table test (name text)");
        do_exec (db, "insert into test (name) values ('test1')");
        do_exec (db, "insert into test (name) values ('test2')");
        do_exec (db, "insert into test (name) values ('test3')");
        do_exec (db, "insert into test (name) values ('test4')");
    }

    int cols[1];
    int handle = sqlite_query (db, "select * from test", cols);

    while (sqlite_next_row (handle) == 1) {
        for (int i = 0; i < cols[0]; i++)
            Print (sqlite_get_col (handle, i));
    }

    sqlite_free_query (handle);

    return (0);
}

Pretty simple, isn't it?

Personal tools