求对Access数据库进行查询的VC++实例代码

2024-11-19 23:32:28
推荐回答(2个)
回答1:

#include
#include
#include
#include

int main(){
MYSQL *mysql;
MYSQL_RES *res;
MYSQL_ROW row;
char query[1024];
int t,r;

mysql=mysql_init(NULL);
if (!mysql_real_connect(mysql,"test","root",
"123","test",0,NULL,0))
{
printf( "Error connecting to database: %s\n",mysql_error(mysql));
}
else printf("Connected...\n");

sprintf(query,"select * from first");

t=mysql_query(mysql,query);

if (t)
{
printf("Error making query: %s\n",
mysql_error(mysql));
}
else printf("Query made...\n");
res=mysql_use_result(mysql);
for(r=0;r row=mysql_fetch_row(res);
if(row<0) break;
for(t=0;t printf("%s",row[t]);
printf("\n");
}
mysql_close(mysql);
return 0;
}

回答2:

为什么不用ADO?
stdafx.h中导入msado15.dll
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename ("EOF", "adoEOF")
然后在用到数据库的类中加成员变量:
_ConnectionPtr m_pConnection;
_RecordsetPtr m_pDBRec;
的构造函数中加入
CoInitialize(NULL);
m_pConnection.CreateInstance(__uuidof(Connection));
try
{
//str是控制字符串
m_pConnection->Open( str.GetBuffer(str.GetLength()), "", "", adModeUnknown );
}
catch(_com_error e)
{
AfxMessageBox(e.ErrorMessage());
}

m_pDBList.CreateInstance(__uuidof(Recordset)); m_pDBList->CursorLocation = adUseClient;

之后就可访问了。