VC++ 訪问数据库实例具体解释图解

一 ADO 方式訪问 Access

新建一个对话框project,加入控件,如图;


创建Access数据库如图;



应用程序启动时进行COM初始化。

BOOL CDemoApp::InitInstance()
{
if (!SUCCEEDED(CoInitialize(NULL)))
{
::AfxMessageBox(_T("Failed to initialize COM!"));
return FALSE;
}

AfxEnableControlContainer();


对话框类实现文件代码例如以下;

// DemoDlg.cpp : implementation file
// Download by http://www.NewXing.com


#include "stdafx.h"
#include "Demo.h"
#include "DemoDlg.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About


class CAboutDlg : public CDialog
{
public:
CAboutDlg();


// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA


// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
//}}AFX_VIRTUAL


// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};


CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}


void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()


/////////////////////////////////////////////////////////////////////////////
// CDemoDlg dialog


CDemoDlg::CDemoDlg(CWnd* pParent /*=NULL*/)
: CDialog(CDemoDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CDemoDlg)
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);


if (!SUCCEEDED(m_pConnection.CreateInstance(__uuidof(Connection))))
{
m_pConnection = NULL;
TRACE(_T("Database CreateInstance failed"));
}


if (!SUCCEEDED(m_pRecordset.CreateInstance(__uuidof(Recordset))))
{
m_pRecordset = NULL;
TRACE(_T("Recordset CreateInstance Failed!"));
}


//打开数据库
CString strConnect = _T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= Demo.mdb");
if (!OpenDatabase(strConnect))
{
AfxMessageBox(_T("数据库打开失败。

"));
return;
}

//打开记录集
if (!OpenRecordset(_T("SELECT * FROM DemoTable")))
{
AfxMessageBox(_T("记录集打开失败。"));
return;
}
}


CDemoDlg::~CDemoDlg()
{
m_pRecordset->Close();
m_pConnection->Close();
}


void CDemoDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDemoDlg)
//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CDemoDlg, CDialog)
//{{AFX_MSG_MAP(CDemoDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_FIND, OnFind)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()


/////////////////////////////////////////////////////////////////////////////
// CDemoDlg message handlers


BOOL CDemoDlg::OnInitDialog()
{
CDialog::OnInitDialog();


// Add "About..." menu item to system menu.


// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);


CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}


// Set the icon for this dialog.  The framework does this automatically
//  when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE);// Set big icon
SetIcon(m_hIcon, FALSE);// Set small icon


//初始化ListCtrl
CListCtrl* pListCtrl = (CListCtrl*)GetDlgItem(IDC_LIST);
pListCtrl->SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
pListCtrl->InsertColumn(1, _T("序号"), LVCFMT_CENTER, 80);
pListCtrl->InsertColumn(2, _T("姓名"), LVCFMT_CENTER, 100);
pListCtrl->InsertColumn(3, _T("年龄"), LVCFMT_CENTER, 100);


return TRUE;
}


void CDemoDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}


// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.


void CDemoDlg::OnPaint() 
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting


SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);


// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;


// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}


// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CDemoDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}


BOOL CDemoDlg::OpenDatabase(LPCTSTR lpszConnect, long nOptions)
{
ASSERT(m_pConnection != NULL);
ASSERT(lpszConnect != NULL);
ASSERT(AfxIsValidString(lpszConnect));

//打开数据库连接
try
{
return SUCCEEDED(m_pConnection->Open(_bstr_t(lpszConnect), 
_T(""), _T(""), nOptions));
}
catch (_com_error& e)
{
TRACE(_T("%s "), e.ErrorMessage());
return FALSE;
}
}


BOOL CDemoDlg::CloseDatabase()
{
ASSERT(m_pConnection != NULL);


//关闭数据库连接
try
{
if (m_pConnection->State & adStateOpen) 
{
return SUCCEEDED(m_pConnection->Close());
}
else
{
return TRUE;
}
}
catch (_com_error& e)
{
TRACE(_T("%s "), e.ErrorMessage());
return FALSE;

}


BOOL CDemoDlg::OpenRecordset(LPCTSTR lpszSource, long nCursorType, long nLockType, long nOptions)
{
ASSERT(m_pConnection != NULL);
ASSERT(m_pRecordset != NULL);
ASSERT(lpszSource != NULL);
ASSERT(AfxIsValidString(lpszSource));


//打开记录集
try
{
return (SUCCEEDED(m_pRecordset->Open(_variant_t(lpszSource),
m_pConnection.GetInterfacePtr(),
(CursorTypeEnum)nCursorType, 
(LockTypeEnum)nLockType,
nOptions)));
}
catch(_com_error e)
{
TRACE(_T("%s "), e.ErrorMessage());
return FALSE;
}
}


BOOL CDemoDlg::CloseRecorset()
{
ASSERT(m_pRecordset != NULL);


//关闭记录集
try
{
if (m_pRecordset->State & adStateOpen) 
{
return SUCCEEDED(m_pRecordset->Close());
}
else
{
return TRUE;
}
}
catch (_com_error e)
{
TRACE(_T("%s "), e.ErrorMessage());
return FALSE;
}
}


void CDemoDlg::OnFind() 
{
if (!(m_pRecordset->State & adStateOpen))
{
AfxMessageBox((_T("记录集未打开。

")));
return;
}


//查找条件
CString strCriteria = _T("");
CString strName = _T("");
GetDlgItemText(IDC_NAME, strName);
strCriteria.Format(_T("NAME like '%s'"), strName);


//查找记录集
CListCtrl* pListCtrl = (CListCtrl*)GetDlgItem(IDC_LIST);
pListCtrl->DeleteAllItems();
if (m_pRecordset->BOF && m_pRecordset->adoEOF)
{
return;
}
m_pRecordset->MoveFirst();
int n = 0;
m_pRecordset->Find(_bstr_t(strCriteria), 0, adSearchForward);
while (!m_pRecordset->adoEOF)
{
_variant_t varValue;
CString strName = _T("");
int nAge = 0;


varValue = m_pRecordset->GetCollect(_variant_t(_T("NAME")));
if (varValue.vt != VT_NULL)
{
strName = varValue.bstrVal;
}
else
{
strName = _T("");
}


varValue = m_pRecordset->GetCollect(_variant_t(_T("AGE")));
if (varValue.vt != VT_NULL)
{
nAge = varValue.intVal;
}
else
{
nAge = 0;
}


//刷新ListCtrl
CString strText = _T("");
strText.Format(_T("%d"), n + 1);
pListCtrl->InsertItem(n, strText);
strText.Format(_T("%s"), strName);
pListCtrl->SetItemText(n, 1, strText);
strText.Format(_T("%d"), nAge);
pListCtrl->SetItemText(n, 2, strText);
n++;


m_pRecordset->Find(_bstr_t(strCriteria), 1, adSearchForward);
}
}

折叠起来看下函数。

代码就不解释了;函数含义比較明白。除了操作数据库。ADO方式还有COM相关操作。

效果:


VC在调试时。Data Source= Demo.mdb。这种语句,訪问的不是Debug文件夹下的Demo.mdb,是和Debug文件夹同级;

假设Debug文件夹同级没有数据库,则打开数据库失败。





project下载

http://pan.baidu.com/s/1slEEOMD

Access工具下载

http://blog.csdn.net/bcbobo21cn/article/details/51000041

VC6下载

http://blog.csdn.net/bcbobo21cn/article/details/44200205

二 VC 訪问 sqlite3

首先用sqlite3创建一个数据库,设备db。


创建表并插入数据;


接下来在VC6中新建一个控制台project。

代码。

#include <stdio.h> 
#include <stdlib.h> 
#include <sqlite3.h> 
int column_names_printed = 0; 
void print_row(int n_values, char** values) 

    int i; 
    for (i = 0; i < n_values; ++i) { 
        printf("%10s", values[i]); 
    } 
    printf(" "); 

int print_result(void* data, int n_columns, char** column_values, char** column_names) 

    if (!column_names_printed) { 
        print_row(n_columns, column_names); 
        column_names_printed = 1; 
    } 
    
    print_row(n_columns, column_values); 
   
   return 0; 

int main() 

    sqlite3 *db=NULL; 
    char *errMsg = NULL; 
    int rc; 
    
    rc = sqlite3_open("shebei.db", &db); 
    if( rc ){ 
        fprintf(stderr, "Can't open database: %s ", sqlite3_errmsg(db)); 
        sqlite3_close(db); 
        exit(1); 
    } 
    else printf("open shebei.db successfully! "); 
    
    column_names_printed = 0; 
    rc = sqlite3_exec(db, "SELECT shebei.* FROM shebei;", print_result, NULL, &errMsg); 
    column_names_printed = 1; 
    printf(" "); 
    
    printf("error code: %d ", rc); 
    printf("error message: %s ", errMsg); 
    sqlite3_close(db); 
    return 0; 

注意假设例如以下的换行语句。

rc = sqlite3_exec(db, "CREATE TABLE students(number varchar(10), name varchar(10),  
                           sex varchar(6), age varchar(2));", NULL, NULL, NULL);
之后假设有空格;则会出现;
Y:dddd20sqlitedemo1demo1.cpp(39) : warning C4129: ' ' : unrecognized character escape sequence

删除空格就可以;


如今我们有sqlite3.dll跟一个sqlite3.def文件,并没实用于VC++6.0的lib文件,能够利用sqlite3.def文件生成,过程例如以下: 
  1.将sqlite3.h(D:sqlite-amalgamation-3_6_23.zip)复制到C:Program FilesMicrosoft Visual StudioVC98Include文件夹下,这时编译可通过,但链接错误,由于没有LIB文件() 
  2.启动一个命令行程序,进入VC的安装文件夹C:Program FilesMicrosoft Visual StudioVC98Bin,在这个文件夹以下有一个LIB.exe文件,使用它就能生成sqlite3.lib文件,将sqlite3.def文件放到同样文件夹,或者绝对路径也能够。 然后在命令行输入例如以下命令: 
   LIB /MACHINE:IX86 /DEF:sqlite3.def 
  该命令生成两个文件:sqlite3.lib和sqlite3.exp 
   执行该命令时。假设提示找不到MSPDB60.DLL文件,可从其他文件夹拷贝至Bin文件夹下 
  3.将生成的sqlite3.lib复制到Lib文件夹下,将sqlite3.dll复制到C:WINNTsystem32文件夹下 
   4.将sqlite3.lib增加到project链接中,Project->Settings,Link选项卡,Object/library modules最后添入sqlite3.lib 

參阅:http://mxdxm.iteye.com/blog/634772

操作过程和完毕结果例如以下图;



把环境配置好;编译执行程序。效果例如以下;



project下载

sqlite相关下载。包含,h、Lib、dll文件;

http://pan.baidu.com/s/1slEEOMD


三 ADO訪问数据库出现C2146、C2501

demodlg.h(25) : error C2146: syntax error : missing ';' before identifier 'm_pConnection'
demodlg.h(25) : error C2501: '_ConnectionPtr' : missing storage-class or type specifiers
demodlg.h(25) : error C2501: 'm_pConnection' : missing storage-class or type specifiers

在stdafx.h中增加例如以下语句再构建;

#import "c:Program Files (x86)common filessystemadomsado15.dll"
no_namespace
rename("EOF", "adoEOF")


另外再看是否少了};

原文地址:https://www.cnblogs.com/llguanli/p/7254020.html