Hello!
I use Zeslib for MySQL database connection. I do it with this code (C is TConnection component already placed in main Form):
var
Q: TZQuery;
begin
{ If we are online }
if not C.Connected then begin
C.HostName := '127.0.0.1';
C.User := 'root';
C.Password := '';
C.Database := 'mydb';
C.Catalog := 'mydb';
try
C.Connect;
except
on E: Exception do begin // catching exeptions
C.Disconnect; // an error has happened => we are going to offline status
if (E.ClassName = 'EZSQLException') and (Copy(E.Message, 0, 33) = 'SQL Error: Access denied for user') then
ShowError('Access denied. You have propably entered incorrect database connection information.', 'Connection error')
else
if (E.ClassName = 'EZSQLException') and (GetMySQLErrorId(E.Message) = '10061') then
ShowError('Connection to database cannot be done.', 'Connection error')
else
ShowError('<unhandled connection message> '+E.Message);
end;
end;
end;
{ If we are already online }
if C.Connected then begin
Q := TZQuery.Create(nil);
Q.Connection := C;
Q.SQL.Text := 'SELECT my_column FROM my_table WHERE id=50;';
try
Q.Open;
ShowInfo(Q.FieldByName('my_column').AsString);
Q.Close;
except
on E: Exception do begin // catching exeptions
C.Disconnect; // an error has happened => we are going to offline status
if E.Message = 'SQL Error: MySQL server has gone away' then
ShowError('Connection to database has been lost.', 'Connection error')
else
ShowError('<unhandled query message> '+E.Message);
end;
end;
Q.Free;
end;
This code works OK but if I want make query, i have to write all these lines. Is there any other way? For example i would write only:
var
Q: TZQuery;
begin
Q := TZQuery.Create(nil);
Q.Connection := C;
Q.SQL.Text := 'SELECT my_column FROM my_table WHERE id=50;';
Q.Open;
ShowMessage(Q.FieldByName('my_column').AsString);
Q.Close;
Q.Free;
... and somewhere else in the code (in global placement which is called everytime when query is trying to make database transaction) will be done code above - for testing wether Connection is online and handling exceptions for connection and for query aswell.
I hope i wrote it clearly.