Здравствуйте, Alexander, Вы писали:
A>В заголовочном файле объявлена сессия CSession m_session
A>Как ее использовать в коде программы?
A>через extern не получается
A>A>error C2071: 'CissaveSetAccessor::m_session' : illegal storage class
Ответ на этот вопрос будет стоить $64000. Дорого? А что вы хотите? Одна амортизация хрустального шара в кругленькую копеечку встанет.
Или вам придётся обнародовать дополнительную информацию. Как минимум, показать следующие куски кода:
— объявление;
— желаемое использование;
— где возникает ошибка.
PS. Задавая вопрос, поставьте себя на место тех, кто будет пытаться помочь вам с ним разобраться, имея перед глазами только полученную от вас информацию. Это очень простое правило.
Необходимо написать функцию для выполнения SQL-запросов.
В
этой теме уже отвечали на подобный вопрос:
CCommand<CNoAccessor, CNoRowset> mRs;
//sSQL - текст оператора, CString
HRESULT hr = mRs.Open(m_session, sSQL);
if(FAILED(hr))
return hr;
mRs.Close();
MFC Wizard сделал проект с поддержкой OLE DB, приложение подключается к базе данных и получает значения из нее.
Но не получается разобраться с кодом выше, точнее с m_session. В проекте, который делает Wizard, m_session объявлена в в классе заголовочного файла:
class CissaveSetAccessor
{
public:
CSession m_session;
Как использовать эту сессию?
Здравствуйте, Chorkov, Вы писали:
C>C>CissaveSetAccessor accessor; // Возможно, конструктор CissaveSetAccessor имеет аргументы? Возможно, у тебя и так уже есть обьект этого класса...
C>mRs.Open( accessor.m_session , sSQL);
C>
Не могу понять, что является объектом класса (приложение делалось в визарде)
В этом случае, возникает assertion error:
[code]
// issaveSet.h: интерфейс класса CissaveSet
//
#pragma once
// code generated on 3 августа 2011 г., 17:47
class CissaveSetAccessor
{
public:
CSession m_session;
TCHAR m_K[11];
TCHAR m_V[11];
// ISequentialStream* m_S;
TCHAR m_S[8000];
// The following wizard-generated data members contain status
// values for the corresponding fields in the column map. You
// can use these values to hold NULL values that the database
// returns or to hold error information when the compiler returns
// errors. See Field Status Data Members in Wizard-Generated
// Accessors in the Visual C++ documentation for more information
// on using these fields.
// NOTE: You must initialize these fields before setting/inserting data!
DBSTATUS m_dwKStatus;
DBSTATUS m_dwVStatus;
DBSTATUS m_dwSStatus;
// The following wizard-generated data members contain length
// values for the corresponding fields in the column map.
// NOTE: For variable-length columns, you must initialize these
// fields before setting/inserting data!
DBLENGTH m_dwKLength;
DBLENGTH m_dwVLength;
DBLENGTH m_dwSLength;
void GetRowsetProperties(CDBPropSet* pPropSet)
{
pPropSet->AddProperty(DBPROP_CANFETCHBACKWARDS, true, DBPROPOPTIONS_OPTIONAL);
pPropSet->AddProperty(DBPROP_CANSCROLLBACKWARDS, true, DBPROPOPTIONS_OPTIONAL);
// pPropSet->AddProperty(DBPROP_ISequentialStream, true);
}
HRESULT OpenDataSource()
{
CDataSource _db;
HRESULT hr;
// #error Security Issue: The connection string may contain a password
// The connection string below may contain plain text passwords and/or
// other sensitive information. Please remove the #error after reviewing
// the connection string for any security related issues. You may want to
// store the password in some other form or use a different user authentication.
hr = _db.OpenFromInitializationString(L"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=firstdb;Data Source=\x0421\x0415\x041c\x042c\x042f-\x041f\x041a\\SQLEXPRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=\x0421\x0415\x041c\x042c\x042f-\x041f\x041a;Use Encryption for Data=False;Tag with column collation when possible=False");
if (FAILED(hr))
{
#ifdef _DEBUG
AtlTraceErrorRecords(hr);
#endif
return hr;
}
return m_session.Open(_db);
}
void CloseDataSource()
{
m_session.Close();
}
operator const CSession&()
{
return m_session;
}
// This table/command contains column(s) that can be accessed
// via an ISequentialStream interface. Not all providers, however,
// support this feature, and even those that do support it, are
// often limited to just one ISequentialStream per rowset.
// If you want to use streams in this accessor, use the sample
// line(s) of code below, and set the DBPROP_ISequentialStream
// rowset propery to true. You can than use the Read() method
// to read the data, or Write() method to write the data (note
// that this requires that you change the STGM_READ stream property
// to STGM_WRITE or STGM_READWRITE). For more information on
// ISequentialStream binding see the documentation
BEGIN_COLUMN_MAP(CissaveSetAccessor)
COLUMN_ENTRY_LENGTH_STATUS(2, m_K, m_dwKLength, m_dwKStatus)
COLUMN_ENTRY_LENGTH_STATUS(3, m_V, m_dwVLength, m_dwVStatus)
// BLOB_ENTRY_LENGTH_STATUS(1, IID_ISequentialStream, STGM_READ, m_S, m_dwSLength, m_dwSStatus)
COLUMN_ENTRY_LENGTH_STATUS(1, m_S, m_dwSLength, m_dwSStatus)
END_COLUMN_MAP()
};
class CissaveSet : public CTable<CAccessor<CissaveSetAccessor> >
{
public:
HRESULT OpenAll()
{
HRESULT hr;
hr = OpenDataSource();
if (FAILED(hr))
return hr;
__if_exists(GetRowsetProperties)
{
CDBPropSet propset(DBPROPSET_ROWSET);
__if_exists(HasBookmark)
{
if( HasBookmark() )
propset.AddProperty(DBPROP_IRowsetLocate, true);
}
GetRowsetProperties(&propset);
return OpenRowset(&propset);
}
__if_not_exists(GetRowsetProperties)
{
__if_exists(HasBookmark)
{
if( HasBookmark() )
{
CDBPropSet propset(DBPROPSET_ROWSET);
propset.AddProperty(DBPROP_IRowsetLocate, true);
return OpenRowset(&propset);
}
}
}
return OpenRowset();
}
HRESULT OpenRowset(DBPROPSET *pPropSet = NULL)
{
HRESULT hr = Open(m_session, L"dbo.Table_1", pPropSet);
#ifdef _DEBUG
if(FAILED(hr))
AtlTraceErrorRecords(hr);
#endif
return hr;
}
void CloseAll()
{
Close();
CloseDataSource();
}
};
[/ccode]
P.S. Эх, совсем я не умею программировать на Visual C++, отсюда такие и вопросы
Неправильно вставилось.
В этом случае возникает assertion error:
---------------------------
Microsoft Visual C++ Debug Library
---------------------------
Debug Assertion Failed!
Program: d:\issave\Debug\issave.exe
File: c:\program files\microsoft visual studio 10.0\vc\atlmfc\include\atldbcli.h
Line: 7068
Expression: session.m_spOpenRowset != 0
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application)
---------------------------
Прервать Повтор Пропустить
---------------------------
Пытался закрыть сессию так:
if(accessor.m_session.m_spOpenRowset != NULL) accessor.m_session.Close();
Не закрывается. Как я понимаю, сессия открыта в объекте, который принадлежит этому классу? Не могу его найти в созданном визардом проекте.
Так выглядит issaveSet.h:
// issaveSet.h: интерфейс класса CissaveSet
//
#pragma once
// code generated on 3 августа 2011 г., 17:47
class CissaveSetAccessor
{
public:
CSession m_session;
TCHAR m_K[11];
TCHAR m_V[11];
// ISequentialStream* m_S;
TCHAR m_S[8000];
// The following wizard-generated data members contain status
// values for the corresponding fields in the column map. You
// can use these values to hold NULL values that the database
// returns or to hold error information when the compiler returns
// errors. See Field Status Data Members in Wizard-Generated
// Accessors in the Visual C++ documentation for more information
// on using these fields.
// NOTE: You must initialize these fields before setting/inserting data!
DBSTATUS m_dwKStatus;
DBSTATUS m_dwVStatus;
DBSTATUS m_dwSStatus;
// The following wizard-generated data members contain length
// values for the corresponding fields in the column map.
// NOTE: For variable-length columns, you must initialize these
// fields before setting/inserting data!
DBLENGTH m_dwKLength;
DBLENGTH m_dwVLength;
DBLENGTH m_dwSLength;
void GetRowsetProperties(CDBPropSet* pPropSet)
{
pPropSet->AddProperty(DBPROP_CANFETCHBACKWARDS, true, DBPROPOPTIONS_OPTIONAL);
pPropSet->AddProperty(DBPROP_CANSCROLLBACKWARDS, true, DBPROPOPTIONS_OPTIONAL);
// pPropSet->AddProperty(DBPROP_ISequentialStream, true);
}
HRESULT OpenDataSource()
{
CDataSource _db;
HRESULT hr;
// #error Security Issue: The connection string may contain a password
// The connection string below may contain plain text passwords and/or
// other sensitive information. Please remove the #error after reviewing
// the connection string for any security related issues. You may want to
// store the password in some other form or use a different user authentication.
hr = _db.OpenFromInitializationString(L"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=firstdb;Data Source=\x0421\x0415\x041c\x042c\x042f-\x041f\x041a\\SQLEXPRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=\x0421\x0415\x041c\x042c\x042f-\x041f\x041a;Use Encryption for Data=False;Tag with column collation when possible=False");
if (FAILED(hr))
{
#ifdef _DEBUG
AtlTraceErrorRecords(hr);
#endif
return hr;
}
return m_session.Open(_db);
}
void CloseDataSource()
{
m_session.Close();
}
operator const CSession&()
{
return m_session;
}
// This table/command contains column(s) that can be accessed
// via an ISequentialStream interface. Not all providers, however,
// support this feature, and even those that do support it, are
// often limited to just one ISequentialStream per rowset.
// If you want to use streams in this accessor, use the sample
// line(s) of code below, and set the DBPROP_ISequentialStream
// rowset propery to true. You can than use the Read() method
// to read the data, or Write() method to write the data (note
// that this requires that you change the STGM_READ stream property
// to STGM_WRITE or STGM_READWRITE). For more information on
// ISequentialStream binding see the documentation
BEGIN_COLUMN_MAP(CissaveSetAccessor)
COLUMN_ENTRY_LENGTH_STATUS(2, m_K, m_dwKLength, m_dwKStatus)
COLUMN_ENTRY_LENGTH_STATUS(3, m_V, m_dwVLength, m_dwVStatus)
// BLOB_ENTRY_LENGTH_STATUS(1, IID_ISequentialStream, STGM_READ, m_S, m_dwSLength, m_dwSStatus)
COLUMN_ENTRY_LENGTH_STATUS(1, m_S, m_dwSLength, m_dwSStatus)
END_COLUMN_MAP()
};
class CissaveSet : public CTable<CAccessor<CissaveSetAccessor> >
{
public:
HRESULT OpenAll()
{
HRESULT hr;
hr = OpenDataSource();
if (FAILED(hr))
return hr;
__if_exists(GetRowsetProperties)
{
CDBPropSet propset(DBPROPSET_ROWSET);
__if_exists(HasBookmark)
{
if( HasBookmark() )
propset.AddProperty(DBPROP_IRowsetLocate, true);
}
GetRowsetProperties(&propset);
return OpenRowset(&propset);
}
__if_not_exists(GetRowsetProperties)
{
__if_exists(HasBookmark)
{
if( HasBookmark() )
{
CDBPropSet propset(DBPROPSET_ROWSET);
propset.AddProperty(DBPROP_IRowsetLocate, true);
return OpenRowset(&propset);
}
}
}
return OpenRowset();
}
HRESULT OpenRowset(DBPROPSET *pPropSet = NULL)
{
HRESULT hr = Open(m_session, L"dbo.Table_1", pPropSet);
#ifdef _DEBUG
if(FAILED(hr))
AtlTraceErrorRecords(hr);
#endif
return hr;
}
void CloseAll()
{
Close();
CloseDataSource();
}
};