VC++ 访问数据库实例详解图解

一 ADO 方式访问 Access

新建一个对话框工程,添加控件,如图;


创建Access数据库如图;

VC++ 访问数据库实例详解图解_第1张图片


应用程序启动时进行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\n"), 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\n"), 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\n"), 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\n"), 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);
}
}

折叠起来看下函数;

VC++ 访问数据库实例详解图解_第2张图片

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

效果:

VC++ 访问数据库实例详解图解_第3张图片


VC在调试时,Data Source= Demo.mdb,这样的语句,访问的不是Debug目录下的Demo.mdb,是和Debug目录同级;

如果Debug目录同级没有数据库,则打开数据库失败;



VC++ 访问数据库实例详解图解_第4张图片


工程下载

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;

VC++ 访问数据库实例详解图解_第5张图片

创建表并插入数据;

VC++ 访问数据库实例详解图解_第6张图片

接下来在VC6中新建一个控制台工程;

代码;

#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("\n"); 

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\n", sqlite3_errmsg(db)); 
        sqlite3_close(db); 
        exit(1); 
    } 
    else printf("open shebei.db successfully!\n"); 
    
    column_names_printed = 0; 
    rc = sqlite3_exec(db, "SELECT shebei.* FROM shebei;", print_result, NULL, &errMsg); 
    column_names_printed = 1; 
    printf("\n"); 
    
    printf("error code: %d\n", rc); 
    printf("error message: %s\n", 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:\dddd20\sqlitedemo1\demo1.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 Files\Microsoft Visual Studio\VC98\Include目录下,这时编译可通过,但链接错误,因为没有LIB文件() 
  2.启动一个命令行程序,进入VC的安装目录C:\Program Files\Microsoft Visual Studio\VC98\Bin,在这个目录下面有一个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:\WINNT\system32目录下 
   4.将sqlite3.lib加入到工程链接中,Project->Settings,Link选项卡,Object/library modules最后添入sqlite3.lib 

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

操作过程和完成结果如下图;

VC++ 访问数据库实例详解图解_第7张图片


把环境配置好;编译运行程序;效果如下;

VC++ 访问数据库实例详解图解_第8张图片


工程下载

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 files\system\ado\msado15.dll"\
no_namespace\
rename("EOF", "adoEOF")


另外再看是否少了};

你可能感兴趣的:(数据库,Access,VC,ADO,VC访问数据库)