Delphi - How build connection string to .mdb that changes directory location

Viewed 398

Bit of a noob here. I am working on school practical in delphi. My project is saved on my one drive and each time I update the programe i create a new version, with a new directory. Example:

blah-blah\OneDrive\PAT(a folder containing all the files from the program including the .mdb)

inside this directory, which does not change, the final folder name, changes. Ex.:

blah-blah\OneDrive\PAT\V1

blah-blah\OneDrive\PAT\V2

blah-blah\OneDrive\PAT\V3 and so on...

My problem is that I am using a .mdb and everytime i copy the files to a new folder structure I have to go and build a new connection string to conntect to my database. I am using a simple ADO Connection.

Any help would be appreciated, Thx in advance!

2 Answers

A connection string is just a string, so you can manipulate it in code just like any other string. The expression ExtractFilePath(Application.ExeName) returns the path to your Exe's location, so all you need to is to set the path component of the Mdb file name to that.

One way to do this would be to define a string constant in your code for the connection string value and put a placeholder in it for the path to the Mdb, like so

const
  scConnectionString = 'blahblahetc%pathtomdb%mymdb.mdbblahetc';

and then use the StringReplace function to substitute the correct path at run-time before you open the connection, as in

var
  APath : String;
[...]
  APath := ExtractFilePath(Application.ExeName);
  AdoConnection1.ConnectionString := StringReplace(scConnectionString, '%pathtomdb%', APath, []);

ADO Connection string can be stored in UDL file, which is actually simple ini file. Then you have to change connection string in UDL file, not in your source code. Universal Data Link (UDL) configuration

Related