HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Querying MySQL from an external application

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
applicationqueryingmysqlexternalfrom

Problem

I have a database that I need to query over and over as fast as possible. My queries execute pretty quickly, but there seems to be some additional lag. I have a feeling that this lag is due to the fact that I am initiating and de-initiating a connection the connection each time. Is there a way to avoid this?

I am not using libmysql (at least, not directly). I am using the "mysql50" package in Lazarus/FreePascal (similar to Delphi), which in turn uses libmysql (I think).

The purpose of this library is to pass along a query sent from MQL4 (a propitiatory C-like language for the financial exchange market), and return a single row from my MySQL database (to which it connects through a pipe).

I would really appreciate if someone took a look at my code and pointed out (or maybe even fixed) some inefficiencies.

{$CALLING STDCALL}

library D1Query;

{$mode objfpc}{$H+}

uses
  cmem,
  Windows,
  SysUtils,
  profs_win32exceptiontrap,
  mysql50;

var

  sock: PMYSQL;
  qmysql: st_mysql;

type
  VArray = array[0..100] of Double;
  PArray = ^VArray;

  procedure InitSQL; stdcall;
  begin

    mysql_init(PMySQL(@qmysql));
    sock :=
      mysql_real_connect(PMysql(@qmysql), '.', 'root', 'password', 'data', 3306, 'mysql', CLIENT_MULTI_STATEMENTS);
    if sock = nil then
    begin
      OutputDebugString(PChar('  Couldn''t connect to MySQL.'));
      OutputDebugString(PChar(mysql_error(@qmysql)));
      halt(1);
    end;

  end;

  procedure DeInitSQL; stdcall;
  begin

    mysql_close(sock);
  end;

  function SQL_Query(QRY: PChar; output: PArray): integer; stdcall;
  var
    rowbuf: MYSQL_ROW;
    recbuf: PMYSQL_RES;
    i: integer;
    nfields: LongWord;

  begin
    InitSQL();

    if (mysql_query(sock, QRY)  nil) then
    begin
      for i:=0 to nfields-1 do
          output^[i] := StrToFloatDef(rowbuf[i], -666);
    end;

    mysql_free_result(recbuf);
    DeInitSQL();
    Result := i;

  end;

exports
  SQL_Query,
  InitSQL,
  DeInitSQL;

begin
end.

Solution

The most important thing here is not to create and destroy the connection as part of executing your query. Force the calling code to create the connection first (or create it yourself if its not done) but dont destroy the connection until the library is unloaded. That should improve speed.

Context

StackExchange Code Review Q#2604, answer score: 3

Revisions (0)

No revisions yet.