program FetchField;

uses GPC, MySQL;

var
  MHandle: PMySQL;
  MRes: PMySQLRes;
  NumFields, i: LongCard;
  Field: PMySQLField;

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 mysql mysqltest }
      Write ('Create table mysqltest');
      if not MySQLQuery (MHandle, 
        'CREATE TABLE mysqltest (nr INT, firstname VARCHAR(100), lastname VARCHAR(100))')
        then
        ErrorTest (MHandle, 'Cannot create table, Please clean up manually!');
      WriteLn ('. done');
      
      { list all fields }
      WriteLn ('List all fields ');
      MRes := MySQLListFields (MHandle, 'mysqltest', nil);
      if MRes = nil then
        ErrorTest (MHandle, 'Cannot list fields. Clean up manually!');
      NumFields := MySQLNumFields (MRes);
      for i := 0 to NumFields - 1 do
        begin
          Field := MySQLFetchField (MRes);
          WriteLn (i + 1, ') ', CString2String (Field^.FieldName))
        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.
