vc++链接sql2008r2 如何多数据库多表查询 如何链接
//c:\Program Files\Common Files\System\ADO\msado15.dll
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize(NULL);
_ConnectionPtr m_pConnection=NULL;
_RecordsetPtr m_pRecordset=NULL;
m_pConnection.CreateInstance(__uuidof(Connection));
m_pRecordset.CreateInstance(__uuidof(Recordset));
_bstr_t strConnect = "Provider=SQLOLEDB.1;Password=123456;Persist Security Info=True;\
User ID=sa;Initial Catalog=test1;Data Source=192.168.1.3";
_bstr_t bstrSQL("select phone from test1.dbo.table1 where class='123'");
try
{
m_pConnection->Open(strConnect, "","", adModeUnknown);
m_pRecordset->Open(bstrSQL, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
_variant_t vstr, vuint;
while (!m_pRecordset->EndOfFile)
{
vuint = m_pRecordset->GetCollect("phone");
unsigned int uintPhone = vuint.ulVal;
//手机号
m_pRecordset->MoveNext();
}
m_pRecordset->Close();
}
catch (_com_error e)
{
return 0;
}
if(m_pConnection->State)
{
m_pConnection->Close();
}
::CoUninitialize();
return 0;
}
大致流程如下 :
1. _bstr_t strConnect = "Provider=SQLOLEDB.1;Password=123456;Persist Security Info=True; User ID=sa;Initial Catalog=test1;Data Source=192.168.1.3";
需要修改成你自己的IP,sa,密码
2. _bstr_t bstrSQL("select phone from test1.dbo.table1 where class='123'");
sql需要改成以下这种:
select phone from test1.dbo.table1 where class='123'
union
select phone from test1.dbo.table2 where class='123'
union
select phone from test2.dbo.table1 where class='123'
union
select phone from test2.dbo.table2 where class='123'
union
....
3. int 可以存下一个手机号吗? 没有问题?
只是举例 但是如果一个数据库有100个表 那不是很长 还有如果test1的数据库表到table1--table99结束 test2数据库表 table100--table200 这样写sql 是不是够呛啊!
select phone from test1.dbo.table2 where class='123'
union
那就写个循环,一个表一个表地查询吧。
int db[] = {100, 200}; //表示第几个数据库中有几个Table1这样的表
for (int i=0; i<2; i++)
for(int j=0; j<db[i]; j++)
{
char szBuf[1000];
sprintf(szBuf, "select phone from test%d.dbo.table%d where class='123'", i+1, j+1);
_bstr_t bstrSQL(szBuf);
.....
}