Voici maintenant l'exemple montrant comment on crée une classe «RecordSet» en utilisant une base de données MySQL:
Uses
mysql4,web;
Const
DataBaseName:Pchar='mabasededonnees_db';
Var
Conn:PMYSQL;
qmysql:TMYSQL;
Procedure InitConnection;Begin
mysql_init(PMySQL(@qmysql));
Conn:=mysql_real_connect(PMysql(@qmysql),nil,'','',nil,0,nil,0);
If(Conn=Nil)Then Begin
Writeln(stderr,'Impossible de se connecter à MySQL.');
Writeln(stderr,mysql_error(@qmysql));
Halt(1);
End;
If mysql_select_db(Conn,DataBaseName)<0Then Begin
Writeln(stderr,'Impossible de sélectionner la base de données.',DatabaseName);
Writeln(stderr,mysql_error(Conn));
Halt(1);
End;
End;
Procedure DoneConnection;Begin
Writeln('Fermeture de la connection de MySQL.');
mysql_close(Conn);
End;
Type RecordSet=Object
Error:Boolean;
ErrCodeStr:PChar;
_Result:PMYSQL_RES;
RowBuf:TMYSQL_ROW;
RecordCount:LongInt;
NumField:SmallInt;
Constructor Init;
Procedure Execute(Const Sql:String);
Function NotEOF:Boolean;
Function f(FieldNum:SmallInt):String;
Procedure MoveNext;
Procedure Close;
End;
Constructor RecordSet.Init;Begin
RecordCount:=0;
NumField:=0;
End;
Procedure RecordSet.Execute(Const Sql:String);
Var
Query:Array[Byte]of Char;
Begin
Query:=Sql;
ErrCodeStr:='';
If mysql_query(Conn,Query)<0Then Begin
Error:=True;
ErrCodeStr:=mysql_error(Conn);
Exit;
End;
_Result:=mysql_store_result(Conn);
If(_Result=Nil)Then Begin
mysql_close(Conn);
RecordCount:=0;
NumField :=0;
End
Else
Begin
RecordCount:=mysql_num_rows(_Result);
NumField :=mysql_num_fields(_Result);
RowBuf :=mysql_fetch_row(_Result);
End;
Error:=False;
End;
Function RecordSet.NotEOF:Boolean;Begin
NotEOF:=RowBuf<>NIL;
End;
Function RecordSet.f(FieldNum:SmallInt):String;Begin
f:=RowBuf[FieldNum];
End;
Procedure RecordSet.MoveNext;Begin
RowBuf:=mysql_fetch_row(_Result);
End;
Procedure RecordSet.Close;Begin
mysql_free_result(_Result);
RecordCount:=0;
NumField:=0;
End;
Var
RS:RecordSet;
BEGIN
WriteLn('Content-Type: text/html; charset=iso-8859-1');
WriteLn;
InitConnection;
RS.Init;
RS.ExecuteRaw('Select * from matablemysql');
While(RS.NotEOF)do Begin
Write ('(Id: ', RS.f(0));
Write (', Champs 1: ', RS.f(1));
Write (', Champs 2 : ', RS.f(2));
Writeln(', Champs 3 : ', RS.f(3),')');
RS.MoveNext;
End;
RS.Close;
DoneConnection;
END.
Dernière mise à jour : Dimanche, le 9 novembre 2014