1

I have a following firebird dataset:

ds1 : TpFIBDataset;

DFM file:

object ds1ID: TFIBIntegerField
 FieldName = 'ID'
end
object ds1FIELD_VALUE: TFIBStringField
  FieldName = 'FIELD_VALUE'
  Size = 250
end

In my Firebird database: ID is integer field and FIELD_VALUE is varchar field.

Delphi 7: Data is being inserted like this

ds1.InsertRecord([123, anyValue]);

here anyValue : variant;

If anyValue = null, null is getting inserted into the database which is the required functionality.

In Delphi XE4, I am doing same like this:

ds1.Insert;
ds1.FieldByName('ID').AsInteger := 123;
ds1.FieldByName('FIELD_VALUE').AsString := anyValue;
ds1.Post;

I get error: could not convert variant of type (null) into type (OleStr)

When I try like this

ds1.Insert;
ds1.FieldByName('ID').AsInteger := 123;
ds1.FieldByName('FIELD_VALUE').AsString := VarToStr(anyValue);
ds1.Post;

Empty string is inserted into the database, but I need null there. What and where should I make change to accomplish this task.

11
  • Do not cast it AsString but use Value then. Or if that TpFIBDataset supports some setting which converts empty string to NULL, use that and try to keep AsString casting. Commented Mar 3, 2014 at 11:35
  • When you say, "I am doing same" that appears not to be true. Your D7 code does ds1.InsertRecord([123, anyValue]);. You don't do that in the XE4 code. Commented Mar 3, 2014 at 11:35
  • @DavidHeffernan - By saying that, I mean I am trying to achieve same functionality but in Delphi XE4 way. Sorry for the creating the confusion. Commented Mar 3, 2014 at 11:36
  • @TLama - We can set EmptyStrToNull property of the field FIELD_VALUE in the dataset, but is not working at all. Commented Mar 3, 2014 at 11:43
  • ds1.FieldByName('FIELD_VALUE').Clear will set the value to NULL, I think Commented Mar 3, 2014 at 11:43

1 Answer 1

4

You need use

ds1.FieldByName('FIELD_VALUE').Value := anyValue;

instead of

ds1.FieldByName('FIELD_VALUE').AsString := anyValue;

There is some difference in this delphi versions. Starting from delphi2006 there is another memory manager that works more precise. In example in delphi 7 and lower you can assign NULL to string or integer value. And comparision NULL with 0 will return true. In greater versions you can't do this. Null is not equal 0 or empty string.

Sign up to request clarification or add additional context in comments.

2 Comments

It has nothing to do with memory manager. Also, are you sure you could ever assign NULL to integer value in Delphi ? I'm sure in Delphi 7 (about which is this question) above you can't. But now the worst, FieldByName returns a reference to a TField object and you're assigning a variant value to it. That won't end up with happy end. I'm not voting down but this answer is wrong.
Tnx a lot, I forgot about .Value. Now added it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.