Board index » delphi » Null value assignments from Database Queries

Null value assignments from Database Queries

I have just started using Delphi 3.0 Client/Server version.
I am converting an existing database application to Delphi and SQL.

I have a TQuery object and am retrieving field values using the following
syntax;

string_variable := QueryObject ['field_name'];

where QueryObject is the name of my TQuery object which has a  record
active.

The problem is when the field value is null the system throws an exception.

I can go: try .... except end;
but I would have to do this several thousand times over the course of the
application and it looks messy.

Is there a way to avoid this, should I use variant data types to handle
nulls and the true string values or should I modify the Delphi libraries to
stop throwing exceptions (is this possible?).

If anyone has a solution to this problem or can make any other suggestions
please
reply. Cheers.

 

Re:Null value assignments from Database Queries


Quote
> I have a TQuery object and am retrieving field values using the
> following
> syntax;

> string_variable := QueryObject ['field_name'];

First, it's never a good programming practice to use variant data types
in Delphi (see the docs, Borland also discourages use of variants) for
(at least) two reasons: variants have a significant overhead while
getting & setting values, and code that uses variants heavily is hard to
maintain later (the next day).

So, either use persistent field objects (using fields editor at
desing-time) or, if the program works on volatile/unrecognized data
structures, use QueryObject.Fields[i].AsXXX format. From the above
example, it seems that you know the underlying data types, it's possible
to use any of the above:

string_variable := QueryObjectField_Name.AsString;
or
string_variable := QueryObject .FieldByName('field_name').AsString;

This will eliminate the null values problem.

Quote
> ... or should I modify the Delphi libraries to
> stop throwing exceptions (is this possible?).

Do not even try! You'll hurt yourself.

Regards.

Other Threads