我有一个Dbf表,我需要在该列中插入年和日期,该程序不会产生任何错误,但该列为空
我尝试使用查询SQL查询,但失败了
procedure TForm1.Button1Click(Sender: TObject);
var year:string;
pogr_d:string;
begin
pogr_d:='';
year:='';
year:=copy(formatdatetime('yyyy',(DateTimePicker1.Date)),1,4);
Label1.Caption:=year;
Label2.Caption:=pogr_d;
if opendialog1.Execute then
if opendialog1.Filename <> null then
begin
TextReader1.FileName := opendialog1.FileName;
try
ImportFromText.Execute;
FDQuery1.Close;
FDQuery1.Active;
FDQuery1.SQL.Text:='update g_rabn.dbf set
year='+''''+year+'''' +' where year='+''''+'''';
FDQuery1.ExecSql;
Except
On E : Exception Do
ShowMessage(E.Message);
end;
end;
end;
end.
答案 0 :(得分:0)
您确定年份包含空字符串吗?可以为NULL吗?您可以尝试以下sql:
'update g_rabn.dbf set year='+''''+year+'''' +' where coalesce(year,'''')='+''''+''''
答案 1 :(得分:0)
您可以使用此代码作为示例。我假设[日期]和[年份]字段为NVARCHAR(4)类型。我还假设您已经设置了数据库连接FConn。
要重现此示例,您将需要一个具有DBGrid1,DateTimePicker1,Edit1,ADOQuery1,ADOQuery2,DataSource1的Form1和两个按钮:Button1插入新记录,而Button2更新现有记录。
通过DataSource1将DBGrid1链接到ADOQuery1。
uses
ADODB, DB, DateUtils;
type
TForm1 = class(TForm)
...
private
{ Private declarations }
FConn: TADOConnection;
FYear: Integer;
FMonth: Integer;
FDay: Integer;
FYearUpd: String;
...
const
SQL1 = 'INSERT [Dbf] ([Date], [Year]) VALUES (''%s%s'', ''%s'')';
SQL2 = 'UPDATE [Dbf] SET [Year] = ''%s'' WHERE Year = ''%s''';
procedure TForm1.FormCreate(Sender: TObject);
begin
// FConn connection initialization
ADOQuery1.Connection := FConn;
ADOQuery2.Connection := FConn;
ADOQuery1.SQL.Text := 'SELECT * FROM Dbf';
ADOQuery1.Open;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
FYear := YearOf(DateTimePicker1.Date);
FMonth := MonthOf(DateTimePicker1.Date);
FDay := DayOf(DateTimePicker1.Date);
// Inserting a new record.
ADOQuery2.SQL.Text := Format(SQL1, [IntToStr(FDay), IntToStr(FMonth), IntToStr(FYear)]);
ADOQuery2.ExecSQL;
// Refreshing the DBGrid.
ADOQuery1.Close;
ADOQuery1.Open;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
FYear := YearOf(DateTimePicker1.Date);
FYearUpd := Trim(Edit1.Text);
// Updating existing records.
ADOQuery2.SQL.Text := Format(SQL2, [FYearUpd, IntToStr(FYear)]);
ADOQuery2.ExecSQL;
// Refreshing the DBGrid.
ADOQuery1.Close;
ADOQuery1.Open;
end;