简体   繁体   English

我如何获取一个TDataset来存储空字符串而不是null?

[英]How do i get a TDataset to store empty string instead of null?

I have a required field in my database (NOT NULL), but empty strings are allowed. 我的数据库中有一个必填字段(NOT NULL),但允许使用空字符串。

How do I get a delphi TDataset to work with this? 我如何获得一个delphi TDataset来使用它? With the required property of the field object set to either true or false it still seems to be trying to store null instead of an empty string. 将字段对象的required属性设置为true或false时,它似乎仍试图存储null而不是空字符串。

For info im using a TIBDataset and a TIBStringField. 有关信息,请使用TIBDataset和TIBStringField。

Normally, you can set the value in the OnBeforePost like this: 通常,您可以像这样在OnBeforePost设置值:

if IBDataSet1.FieldByName('OPTION_TEXT').IsNull then
begin
  IBDataset1.FieldByName('OPTION_TEXT').Value = '';
end;

However, TIBStringField has an unpublished property EmptyAsNull which you must set to False . 但是,TIBStringField具有未发布的属性EmptyAsNull ,您必须将其设置为False The default value is True . 默认值为True When this feature is enabled, the dataset does you a favor and converts empty strings to NULL : 启用此功能后,数据集将帮您一个忙,并将空字符串转换为NULL

You can turn it off like this: 您可以这样关闭它:

if IBDataSet1.FieldByName('OPTION_TEXT').IsNull then
begin
  TIBStringField(IBDataset1.FieldByName('OPTION_TEXT')).EmptyAsNull := False;
  IBDataset1.FieldByName('OPTION_TEXT').Value = '';
end;

Alternatively, you could set the EmptyAsNull property on the string fields in your form's OnCreate if you are using static (design time) fields, or wherever your create your fields. 另外,如果您使用的是静态(设计时)字段,或者在任何创建字段的位置,都可以在窗体的OnCreate的字符串字段上设置EmptyAsNull属性。

TField has property for default value, but it is string and unfortunately empty string means that there is no default value, so it doesn't help in your case. TField具有默认值的属性,但它是字符串,不幸的是,空字符串表示没有默认值,因此对您的情况没有帮助。 But you can catch OnBeforePost event from dataset and check, if field is NULL then set it up with empty string. 但是您可以从数据集中捕获OnBeforePost事件并检查是否字段为NULL,然后使用空字符串进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM