|
|
#include "ado.h"
|
|
|
|
|
|
_ConnectionPtr m_pConnection;
|
|
|
_RecordsetPtr m_pRecordset;
|
|
|
HRESULT hr;
|
|
|
|
|
|
bool open(char* username, char* password, char* dbname, char* ip)
|
|
|
{
|
|
|
try
|
|
|
{
|
|
|
::CoInitialize(NULL); //初始化COM环境
|
|
|
m_pConnection.CreateInstance(__uuidof(Connection)); //创建连接对象
|
|
|
char connStr[200] = "";
|
|
|
sprintf(connStr, "Provider=SQLOLEDB;Data Source=%s;Initial Catalog=%s;", ip, dbname);
|
|
|
hr = m_pConnection->Open(connStr, username, password, -1);
|
|
|
if (hr != S_OK)
|
|
|
return true;
|
|
|
}
|
|
|
catch (_com_error e)
|
|
|
{
|
|
|
return true;
|
|
|
}
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 有输入参数的查询
|
|
|
int QuerySQL(char* SQL, int inputValueCount, int* outputColumn, int* outputValueCount, char**** outputValue)
|
|
|
{
|
|
|
|
|
|
Fields* fields = NULL;
|
|
|
long ColCount = 0;
|
|
|
|
|
|
*outputColumn = 0;
|
|
|
*outputValueCount = 0;
|
|
|
m_pRecordset.CreateInstance(__uuidof(Recordset));
|
|
|
|
|
|
m_pRecordset->Open(SQL, m_pConnection.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText);
|
|
|
hr = m_pRecordset->get_Fields(&fields); //得到记录集的字段集和
|
|
|
if (SUCCEEDED(hr))
|
|
|
{
|
|
|
fields->get_Count(&ColCount);
|
|
|
*outputValueCount = (int)ColCount;
|
|
|
}
|
|
|
if (*outputValueCount == 0)
|
|
|
return 0;
|
|
|
int index = 0;
|
|
|
// 开始分配内存并且存储
|
|
|
*outputValue = (char***)calloc((*outputValueCount) + 1, sizeof(char**));
|
|
|
while (!m_pRecordset->adoEOF)
|
|
|
{
|
|
|
(*outputValue)[index] = (char**)calloc((*outputColumn) + 1, sizeof(char*));
|
|
|
for (long i = 0; i < ColCount; i++)
|
|
|
{
|
|
|
BSTR bstrColName = NULL;
|
|
|
fields->Item[i]->get_Name(&bstrColName);
|
|
|
(*outputValue)[index][i] = (char*)calloc(1000, sizeof(char));
|
|
|
_variant_t taskStyle = NULL;
|
|
|
taskStyle = m_pRecordset->GetCollect(bstrColName);
|
|
|
const char* str;
|
|
|
_bstr_t bst_t = (_bstr_t)taskStyle;
|
|
|
str = (const char*)bst_t;
|
|
|
strcpy((*outputValue)[index][i], str);
|
|
|
}
|
|
|
m_pRecordset->MoveNext();///移到下一条记录
|
|
|
index++;
|
|
|
}
|
|
|
return 0;
|
|
|
}
|
|
|
|
|
|
// 执行查询
|
|
|
int QuerySQLNoInputParam(char* SQL, int* outputColumn, int* outputValueCount, char**** outputValue)
|
|
|
{
|
|
|
return QuerySQL(SQL, 0, outputColumn, outputValueCount, outputValue);
|
|
|
}
|
|
|
|
|
|
// 执行删除更新
|
|
|
int ExecuteSQLNoInputParam(char* SQL)
|
|
|
{
|
|
|
printf("(ado)开始操作\n");
|
|
|
return ExecuteSQL(SQL, 0, NULL);
|
|
|
}
|
|
|
|
|
|
int ExecuteSQL(char* SQL, int valueCount, char** value)
|
|
|
{
|
|
|
try
|
|
|
{
|
|
|
m_pConnection->Execute(_bstr_t(SQL), 0, adCmdText);
|
|
|
}
|
|
|
catch (_com_error e)
|
|
|
{
|
|
|
printf("插入失败\n");
|
|
|
printf(e.Description());
|
|
|
return -1;
|
|
|
}
|
|
|
|
|
|
return 0;
|
|
|
}
|
|
|
|
|
|
void close(void)
|
|
|
{
|
|
|
if (m_pRecordset != NULL) {
|
|
|
//m_pRecordset->MoveFirst();
|
|
|
m_pRecordset->Close();
|
|
|
m_pConnection->Close();
|
|
|
}
|
|
|
::CoUninitialize(); //释放环境
|
|
|
} |