Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoInitialize error working with database inside threads

Using Delphi 7, whenever I try to do any database work inside of a thread I get this error:

"CoInitialize has not been called"

I used a simple code containing an ADOConnection.Open inside the thread.

But the same code works fine if it's used in a form any ideas?

like image 335
riad Avatar asked Nov 28 '22 08:11

riad


2 Answers

@mjn: I'm not allowed to comment your remark in the previous answer, so I created a new answer: calling CoInitialize from the constructor is one of typical error programmers do.

Constructor is executed in a context of another thread, but you need to initialize COM on the current thread (when a thread procedure is running i.e. as part of Execute method) see

like image 81
pf1957 Avatar answered Dec 05 '22 10:12

pf1957


procedure TYourThread.execute;
begin
  CoInitialize(nil); 
  FConnection:=TConnection.Create(...);
  try
    ThreadCode ....
  finally
    FConnection.free;
    CoUninitialize;
  end;
end;
like image 43
bummi Avatar answered Dec 05 '22 09:12

bummi