Author: Tomas Rutkauskas
How to create an Access database at runtime
Answer:
Solve 1:
Here is an OP function that will do it for you:
1 2 procedure CreateMSAccessDB(filename: string);
3 var4 DBEngine, Workspace: Variant;
5 const6 {Important to use the following constant as is}7 dbLangGeneral = '';
8 LANGID = 0x0409;
9 CP = 1252;
10 COUNTRY = '0';
11 dbVersion30 = 32;
12 begin13 DBEngine := CreateOleObject('DAO.DBEngine');
14 {DBEngine := CreateOleObject('DAO.DBEngine.35'); For DAO 3.5}15 Workspace := DBEngine.Workspaces[0];
16 try17 Workspace.CreateDatabase(filename, dbLangGeneral, dbVersion30);
18 except19 on EOleException do20 ShowMessage('Database already exists');
21 end;
22 end;
Solve 2:
It's very simple to create a empty Access-Database (*.mdb File) using OLE. It's not
necessary to have MS-Access installed on your computer. If an exception occures the
error message will returned. After creating the DB you can create Tables with
simple SQL-Statements.
23 24 uses comobj, sysutils;
25 26 function CreateAccessDatabase(FileName: string): string;
27 var28 cat: OLEVariant;
29 begin30 result := '';
31 try32 cat := CreateOleObject('ADOX.Catalog');
33 cat.create('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + Filename + ';');
34 cat := NULL;
35 except36 on e: Exception do37 result := e.message;
38 end;
39 end;