Does the datamodule already exist when this code is called? Go to the project options, section "Forms", and drag the datamodule above the main form so that it is auto-created before the mainform, or manually create the datamodule sufficiently early.
I don't know the logics in your applications and thus cannot help you with the best place to open the sql database.