Author: Olivio Moura
Problem/Question/Abstract:
How to create a ODBC SystemDSN with Delphi?
Answer:
This example shows one way to load the ODBC Administrator's DLL (ODBCCP32.DLL) to
create an Access MDB file and ODBC DSN pointing at it. Note that it assumes
current directory for both the DLL and the MDB, but the DLL will be found if in the
WinSys directory which is where it normally is anyway.
Similar operation applies to most driver types, with some modifications. eg: Access
requires the MDB file to exist so you can hook the DSN to it.
Note also that the "CREATE_DB" call is an Access special (MS Jet Engine) and has
other variants like COMPACT_DB and REPAIR_DB. For a full list see either the Jet
Engine Programmers Guide or the MSDN and search for "CREATE_DB".
1
2 const
3 ODBC_ADD_DSN = 1; // Add data source
4 ODBC_CONFIG_DSN = 2; // Configure (edit) data source
5 ODBC_REMOVE_DSN = 3; // Remove data source
6 ODBC_ADD_SYS_DSN = 4; // add a system DSN
7 ODBC_CONFIG_SYS_DSN = 5; // Configure a system DSN
8 ODBC_REMOVE_SYS_DSN = 6; // remove a system DSN
9
10 type
11 TSQLConfigDataSource = function(hwndParent: HWND;
12 fRequest: WORD;
13 lpszDriver: LPCSTR;
14 lpszAttributes: LPCSTR): BOOL; stdcall;
15
16 procedure Form1.FormCreate(Sender: TObject);
17 var
18 pFn: TSQLConfigDataSource;
19 hLib: LongWord;
20 strDriver: string;
21 strHome: string;
22 strAttr: string;
23 strFile: string;
24 fResult: BOOL;
25 ModName: array[0..MAX_PATH] of Char;
26 srInfo: TSearchRec;
27 begin
28 Windows.GetModuleFileName(HInstance, ModName, SizeOf(ModName));
29 strHome := ModName;
30 while (strHome[length(strHome)] <> '\') do
31 Delete(strHome, length(strHome), 1);
32 strFile := strHome + 'TestData.MDB'; // Test Access Rights (Axes = Access)
33 hLib := LoadLibrary('ODBCCP32'); // load from default path
34 if (hLib <> NULL) then
35 begin
36 @pFn := GetProcAddress(hLib, 'SQLConfigDataSource');
37 if (@pFn <> nil) then
38 begin
39 // force (re-)create DSN
40 strDriver := 'Microsoft Access Driver (*.mdb)';
41 strAttr := Format('DSN=TestDSN' + #0 +
42 'DBQ=%s' + #0 +
43 'Exclusive=1' + #0 +
44 'Description=Test Data' + #0 + #0,
45 [strFile]);
46 fResult := pFn(0, ODBC_ADD_SYS_DSN, @strDriver[1], @strAttr[1]);
47 if (fResult = false) then
48 ShowMessage('Create DSN (Datasource) failed!');
49
50 // test/create MDB file associated with DSN
51 if (FindFirst(strFile, 0, srInfo) <> 0) then
52 begin
53 strDriver := 'Microsoft Access Driver (*.mdb)';
54 strAttr := Format('DSN=TestDSN' + #0 +
55 'DBQ=%s' + #0 +
56 'Exclusive=1' + #0 +
57 'Description=Test Data' + #0 +
58 'CREATE_DB="%s"'#0 + #0,
59 [strFile, strFile]);
60 fResult := pFn(0, ODBC_ADD_SYS_DSN, @strDriver[1], @strAttr[1]);
61 if (fResult = false) then
62 ShowMessage('Create MDB (Database file) failed!');
63 end;
64 FindClose(srInfo);
65
66 end;
67
68 FreeLibrary(hLib);
69 end
70 else
71 begin
72 ShowMessage('Unable to load ODBCCP32.DLL');
73 end;
74 end;
|