Esecuzione di una query con parametri
Nell'esempio seguente viene eseguita una query con parametri semplice che recupera i record con un campo age (maggiore di 30) da una tabella in un database di Microsoft Access. Per supportare il parametro , il record utente deve avere una mappa aggiuntiva. Il codice seguente, in un progetto ATL, usa la CCommand
classe anziché la CTable
classe usata nell'esempio precedente, Attraversando un set di righe semplice.
#include <atldbcli.h>
#include <iostream>
using namespace std;
int main()
{
CDataSource connection;
CSession session;
CCommand<CAccessor<CArtists>> artists;
LPCSTR clsid; // Initialize CLSID_MSDASQL here
LPCTSTR pName = L"NWind";
// Open the connection, session, and table, specifying authentication
// using Windows NT integrated security. Hard-coding a password is a major
// security weakness.
connection.Open(clsid, pName, NULL, NULL, DBPROP_AUTH_INTEGRATED);
session.Open(connection);
// Set the parameter for the query
artists.m_nAge = 30;
artists.Open(session, "select * from artists where age > ?");
// Get data from the rowset
while (artists.MoveNext() == S_OK)
{
cout << artists.m_szFirstName;
cout << artists.m_szLastName;
}
return 0;
}
Il record utente, CArtists
, è simile all'esempio seguente:
class CArtists
{
public:
// Data Elements
CHAR m_szFirstName[20];
CHAR m_szLastName[30];
short m_nAge;
// Column binding map
BEGIN_COLUMN_MAP(CArtists)
COLUMN_ENTRY(1, m_szFirstName)
COLUMN_ENTRY(2, m_szLastName)
COLUMN_ENTRY(3, m_nAge)
END_COLUMN_MAP()
// Parameter binding map
BEGIN_PARAM_MAP(CArtists)
SET_PARAM_TYPE(DBPARAMIO_INPUT)
COLUMN_ENTRY(1, m_nAge)
END_PARAM_MAP()
};