program SimpleQuery;

uses GPC, MySQL;

var
  MHandle: PMySQL;
  MRes: PMySQLRes;
  MRow: PMySQLRow;
  NumFields, NumRows, i, j: LongCard;

procedure ErrorTest (Handle: PMySQL; ErrStr: TString);
begin
  WriteLn (StdErr, ErrStr);
  WriteLn (StdErr, 'Error Code ', MySQLError (Handle));
  Halt (1)
end;

begin
  MHandle := MySQLInit (nil);
  if MySQLRealConnect (MHandle, '', '', '', 'test', 0, nil, 0) = nil then
    begin
      WriteLn (StdErr, 'Cannot connect to MySQL Server');
      WriteLn (StdErr, 'Error Code ', MySQLError (MHandle))
    end
  else
    begin
      { Create the Database }
      Write ('Create database test_mysqlunit4...');
      if not MySQLQuery (MHandle, 'CREATE DATABASE test_mysqlunit4') then
        ErrorTest (MHandle, 'Cannot create database test_mysqlunit4');
      WriteLn ('. done');

      { Select this DB }
      Write ('Select created database...');
      if not MySQLSelectDB (MHandle, 'test_mysqlunit4') then
        ErrorTest (MHandle, 'Cannot select database');
      WriteLn ('. done');

      { Create table flowers }
      Write ('Create table flowers...');
      if not MySQLQuery (MHandle, 
        'CREATE TABLE flowers (nr INT, flowername VARCHAR(100))')
        then
        ErrorTest (MHandle, 'Cannot create table, Please clean up manually!');
      WriteLn ('. done');

      { Populate the Table }
      Write ('Populate the table...');
      if not MySQLQuery (MHandle, 'INSERT INTO flowers VALUES (1, ''Rose'')') then
        ErrorTest (MHandle, 'Cannot populate table, Please clean up manually!');
      if not MySQLQuery (MHandle, 'INSERT INTO flowers VALUES (2, ''Cyclamen'')') then
        ErrorTest (MHandle, 'Cannot populate table, Please clean up manually!');
      if not MySQLQuery (MHandle, 'INSERT INTO flowers VALUES (3, ''Pansy'')') then
        ErrorTest (MHandle, 'Cannot populate table, Please clean up manually!');
      WriteLn ('done');

      { Query the data }
      if not MySQLQuery (MHandle, 'SELECT * FROM flowers') then
        ErrorTest (MHandle, 'Cannot SELECT, Please clean up manually!');
      MRes      := MySQLStoreResult (MHandle);
      NumFields := MySQLNumFields (MRes);
      NumRows   := MySQLNumRows (MRes);
      
      WriteLn ('Rows: ', NumRows, ' Fields per row: ', NumFields);
      
      for i := 0 to NumRows - 1 do
        begin
          MRow := MySQLFetchRow (MRes);
          for j := 0 to NumFields - 1 do
            Write (CString2String (MRow^[j]), ' ');
          WriteLn
        end;
      MySQLFreeResult (MRes);

      { clean up }
      Write ('Clean up');
      if not MySQLQuery (MHandle, 'DROP DATABASE test_mysqlunit4') then
        ErrorTest (MHandle, 'Cannot drop database, Please clean up manually!');
      WriteLn ('. done');
      MySQLClose (MHandle)
    end
end.
