C++ Builder動態(tài)設(shè)定odbc數(shù)據(jù)源
2019-09-06 23:33:31
供稿:網(wǎng)友
本文以access為例
需要文件 odbcinst.h(bcb或vc的include目錄) odbccp32.dll(winntsystem32目錄) implib.exe(通過dll生成lib庫) coff2omf.exe (將coff庫轉(zhuǎn)化為omf庫)
首先將上面文件拷貝到工程目錄,
執(zhí)行下面命令:
implib.exe odbccp32.lib odbccp32.dll
coff2omf odbccp32.lib
下面程序的功能為當(dāng)應(yīng)用程序啟動時(shí),動態(tài)添加/修改一個(gè)指向當(dāng)前目錄的,名為test的系 統(tǒng)數(shù)據(jù)源。
新建一個(gè)工程,在工程主文件(含有winmain函數(shù))中添加
#include <odbcinst.h>
uselib("odbccp32.lib");//lib在工程當(dāng)前目錄
修改后的代碼如下;
//---------------------------------------------------------------------------
#include <vcl.h>
#include <odbcinst.h>
#pragma hdrstop
useform("main.cpp", form1);
//工程的其他單元申明.....
uselib("odbccp32.lib");
//---------------------------------------------------------------------------
winapi winmain(hinstance, hinstance, lpstr, int)
{
/ttry
/t{
/t/t application->initialize();
/t/t ansistring data,datapath,dbpath;
/t/t unsigned char temp[255];//接收轉(zhuǎn)化后的連接字符串
/t/t lpstr ch;//字符串指針相當(dāng)于char *
/t/t datapath=getcurrentdir();//獲取當(dāng)前目錄/t
/t/t data=datapath+"/test.mdb";//假定當(dāng)前數(shù)據(jù)庫為test.mdb
/t/t dbpath="dsn=testdbq="+data+"defaultdir="+datapath+"";
/t/t //構(gòu)造odbc連接字符串,test為數(shù)據(jù)源名,非法字符先用代替
/t/t
/t/t ch=dbpath.c_str();//將ansistring轉(zhuǎn)化為字符串
/t/t int i=0;
/t/t while(*ch!='')//查找并替換非法字符,并裝入字符數(shù)組
/t/t {
/t/t if(*ch=='')
/t/t *ch='';
/t/t temp=*ch;
/t/t ch++;
/t/t i++;
/t/t }
/t/t
/t/t if(::sqlconfigdatasource(null,odbc_add_sys_dsn,(lpstr)"microsoft access driver (*.mdb)",(lpstr)temp))//修改或添加數(shù)據(jù)源,如果成功,程序正常啟動
/t {
/t/t
/t/t application->title = "動態(tài)設(shè)定odbc數(shù)據(jù)源";
/t/t application->createform(__classid(tform1), &form1);
/t/t
/t/t application->run();
/t/t }
/t/t else
/t/t {
/t/t showmessage("數(shù)據(jù)庫設(shè)定失敗!");
/t/t application->terminate();
/t/t }
/t}
/tcatch (exception &exception)
/t{
/t/t application->showexception(&exception);
/t}
/treturn 0;
}