access violation at address 00508B5E in module 'project.exe' Read of address 000

access violation at address 00508B5E in module project.exe Read of address 00000000procedure TFor

access violation at address 00508B5E in module 'project.exe' Read of address 00000000
procedure TForm1.Button5Click(Sender: TObject);
var
  index,i,j:Integer;
  FilePath,Code,County,formula:string;
  DB:Database;
  DAOQuery2:TDAoquery;
  function getprice(code,county,currentstr:string):string; //这里的code传入的是库编码,对数据库进行一次查询返回county
  begin
  with DAOQuery2 do
  begin
  Close;
  SQL.Clear;
  SQL.Add('select '+County+' from '+currentstr+' where 材料编码 in (select 材料编码 from MonDYB where 库编码='+QuotedStr(code)+')');
  Open;
  result:=FieldByName(County).AsString;
  end;
  end;
begin
  with DAOQuery1 do
  begin
  Close;
  SQL.Clear;
  SQL.Add('select * into MonthPrice from Monformwork');// 复制临时表monthprice 
  Execute(0);
  SQL.Clear;
  SQL.Add('select * from MonthPrice');//怪临时表记录集
  open;
  First;//取第一条记录
  while not eof do 
  begin
  Code:=FieldByName('库编码').AsString;//取第一条记录集中的所需要的一个字段做为下面函数的参数
  for i:=4 to fieldcount-1 do //对这条记录的的第五个字段至第最后一个字段循环进行处理
  begin
  County:=Fields[i].FieldName; //取第五个字段做为函数的参数
  DAOQuery2.Create(Application); //动态建立一个query
  DAOQuery2.Database:=DAODatabase1; 
  with DAOQuery2 do //进行第五个字段的处理 
  begin
  Close;
  SQL.Clear;
  SQL.Add('select 转换公式 from MonDYB where 库编码='+QuotedStr(code));
  Open;
  formula:=FieldByName('转换公式').AsString;
  index:=pos('{',formula);
  while index > 0 do
  begin
  j:=pos('}',formula);
  formula:=copy(formula,1,index-1)+getprice(copy(formula,index+1,j-index-1),County,currentstr)+copy(formula,j+1,length(formula)-j);
  index:=pos('{',formula);
  Close;
  SQL.Clear;
  SQL.Add('update Monthprice set '+County+'='+formula+' where 库编码='+QuotedStr(code));
  Execute(0);
  end;
  end;
  end;
  end;
  next;
  end;
end;

帮我看看哪里出问题了?


[解决办法]
DAOQuery2.Create(Application); //动态建立一个query 
//这句应该这样写
DAOQuery2:=TDAoquery.Create( Owner ); 
try
....
finally
DAOQuery2.free;
end;


另外你应该把DAOQuery2创建过程放到循环以外来做,在循环里频繁的创建与销毁对象效率非常低