一.環境及建立一個資料庫
程式設計環境:VS2010
資料庫:access2007
OTL庫載位址:http://otl.sourceforge.net/home.htm
使用access2007建立一個資料庫 MetGS.accdb ,表名為:ModelInfo
二. 添加使用者資料庫源
控制台---管理工具---資料源(ODBC)-----使用者DSN---點選添加
如下圖所示,選擇Microsoft Access Driver(*.mdb,*accdb).
Access安裝如下圖。
這裡兩點需要修改,修改後,然後點選确認就可以
(1)資料庫源名(N),這個随意填寫,我這裡使用:MetGS
(2)資料庫選擇,包含剛才建立 MetGS.accdb的路徑。
完成後就多出一個MetGS
三, 建立一個程式設計環境
(1)使用VS2010建立一個控制台的應用程式,然後需要把otlv4.h檔案複制到對應的環境中,如下圖所示:
(2)寫程式,簡單的測試代碼如下。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define OTL_ODBC
#include "otlv4.h" // include the OTL 4.0 header file
void print(otl_connect& db)
{
//由于權限問題,access 2007 b不支援修改使用者和使用者組
//沒有實作直接從資料庫擷取表名,
//char db_buf[32]={};
//otl_stream stream1(50,"select name from MSysObjects where type=1 and flags=0",db);
//stream1>>db_buf;
//直接使用表名
char db_buf[]="ModelInfo";
char buf[128]={};
sprintf_s(buf,"select * from %s",db_buf);
otl_stream stream(50,buf,db);
//MG m;
int f1;
char f2[32]="";
int f3;
char f4[32]="";
int f5;
char f6[32]="";
while(!stream.eof())
{
stream>>f1>>f2>>f3>>f4>>f5>>f6;
cout<<f1<<" "<<f2<<" "<<f3<<" "<<f4<<" "<<f5<<" "<<f6<<endl;
}
}
int main()
{
otl_connect db;
otl_connect::otl_initialize();
try{
db.rlogon("Admin/[email protected]"); //登入資料庫
cout<<"connnect succes"<<endl<<endl;
print(db);
}catch(otl_exception & p)
{
cerr<<p.msg<<endl;
cerr<<p.stm_text<<endl;
cerr<<p.sqlstate<<endl;
cerr<<p.var_info<<endl;
}
db.logoff();
getchar();
return 0;
}
顯示結果:
總結:
(1)連結資料庫這塊,花了好幾個小時,一直出現這個問題。
開始使用的是這種連接配接方式:
db.rlogon("Driver={Microsoft Access Driver(*.mdb,*accdb)};DBQ=\"E:\CODE_test\Test\MetGS.accdb\";Uid=Admin;Pwd=admin"); //不成功
最後的解決方案是:增加一個資料庫源,db.rlogon("Admin/[email protected]"); //登入資料庫,登入成功
(2)沒有解決的權限問題,根據資料庫獲得表名稱。“show tables”不能再access中使用。
使用語句:select name from MSysObjects where type=1 and flags=0
可以在access 2007中成功查詢表名稱,但是在程式中出現如下問題。
網上的解決方案如下,但是發現隻适合access2003,最後直接用表查詢。
打開您的ACCESS資料庫,然後
工具 -> 選項 -> 視圖 -> 隐藏對象、系統對象
前面的勾選上。
工具 -> 安全 -> 使用者與組的權限