Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Visual C++/MFC/WTL > Подключений БД MS Access в MS VS C++ 2008


Автор: Kauzman 16.5.2008, 21:05
Здраствуйте! Помогите! как подключить БД MS Access в MS VS C++ 2008 в MFC(.exe)?????

Автор: Fighter 17.5.2008, 00:49
Создавай проект с базами данных, с поддержкой OLE DB. Когда нажмешь на кнопку data source появится окошко, в котором нужно собрать строку подключения. ТАм выберешь Microsoft Jet 4.0. 

Автор: Kauzman 17.5.2008, 11:34
Он ошибку выдает! Цитирую: "Error in SelectDataSource(); Could not open data source"! Что с этим делать?

Добавлено через 4 минуты и 47 секунд
А с раза 4 заработал! СПАСИБО!

Автор: Kauzman 17.5.2008, 12:09
Все подключает но при компиляции выдает 4 ошибки:

1>2Doc.cpp
1>c:\users\dennis\documents\visual studio 2008\projects\2\2\2set.h(64) : fatal error C1189: #error :  Security Issue: The connection string may contain a password
1>2View.cpp
1>c:\users\dennis\documents\visual studio 2008\projects\2\2\2set.h(64) : fatal error C1189: #error :  Security Issue: The connection string may contain a password
1>2Set.cpp
1>c:\users\dennis\documents\visual studio 2008\projects\2\2\2set.h(64) : fatal error C1189: #error :  Security Issue: The connection string may contain a password
1>Generating Code...
1>Build log was saved at "file://c:\Users\Dennis\Documents\Visual Studio 2008\Projects\2\2\Debug\BuildLog.htm"
1>2 - 4 error(s), 0 warning(s)

Что теперь делать?

Автор: dizzy1984 19.5.2008, 07:11
Покажи код на который выдаются ошибки

Автор: Kauzman 19.5.2008, 21:28
Ну они одинаковые!
Первая: 
#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=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=F:\\\x0414\x0435\x043d\x0438\x0441\\\x0421\x0435\x0432\x041a\x0430\x0432\x0413\x0422\x0423\\IS-061\\Sess.mdb;Mode=Share Deny None;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Database Password=\"\";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False");
        if (FAILED(hr))
        {
#ifdef _DEBUG
            AtlTraceErrorRecords(hr);
#endif


Вторая:
#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=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=F:\\\x0414\x0435\x043d\x0438\x0441\\\x0421\x0435\x0432\x041a\x0430\x0432\x0413\x0422\x0423\\IS-061\\Sess.mdb;Mode=Share Deny None;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Database Password=\"\";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False");
        if (FAILED(hr))
        {

#ifdef _DEBUG
            AtlTraceErrorRecords(hr);
#endif

Третья:
#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=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=F:\\\x0414\x0435\x043d\x0438\x0441\\\x0421\x0435\x0432\x041a\x0430\x0432\x0413\x0422\x0423\\IS-061\\Sess.mdb;Mode=Share Deny None;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Database Password=\"\";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False");
        if (FAILED(hr))
        {
#ifdef _DEBUG
            AtlTraceErrorRecords(hr);
#endif

Четвертая:
#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=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=F:\\\x0414\x0435\x043d\x0438\x0441\\\x0421\x0435\x0432\x041a\x0430\x0432\x0413\x0422\x0423\\IS-061\\Sess.mdb;Mode=Share Deny None;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Database Password=\"\";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False");
        if (FAILED(hr))
        {
#ifdef _DEBUG
            AtlTraceErrorRecords(hr);
#endif

Автор: Rififi 19.5.2008, 22:08
Читать не пробовал, что там написано?
Please remove the #error after reviewing the connection string for any security related issues

Автор: dizzy1984 20.5.2008, 06:59
Теперь все то, что сказал Rififi, но подробнее
Цитата(Kauzman @  19.5.2008,  23:28 Найти цитируемый пост)
#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.

Директива #error заставляет препроцессор останавливаться и показывать ее как ошибку.
Далее идет комментарий в котором говорится, что в строке подключения к бд может содержаться пароль, который будет виден как в исходном тексте программы, так и, вероятно, в исполняемом файле. Если тебя это устраивает, достаточно далить строку, начинающуюся на директиву #error.

Еще хочу добавить, что в MFC кроме OLE DB (что по моему мнению есть самое худшее из когда либо созданных средств доступа к бд) есть поддержка бд посредством ODBC и DAO. Также существует возможность использовать ADO, которая использует OLE DB, но, по-прежнему, в vc++ это крайне криво.
Поэтому вместо описанного способа я бы посоветовал создать диалоговое приложение MFC, подключить #include <afxdb.h> и работать с классами CDatabase и CRecordset, т.е с ODBC.

Привожу пример кода, читающего значение 1-го поля некоторого запроса.
Подключение
Код

CString connstr = "<строка_подключения_odbc>";
CDatabase db;
try 
{
    db.OpenEx(connstr);
}
catch (CDBException * e)
{
   // Сообщение об ошибке
    e->Delete();    
};

Чтение
Код

CRecordset rs(&db);
rs.Open(AFX_DB_USE_DEFAULT_TYPE, "<текст_запроса>");
CString val;
rs.GetFieldValue("<имя_поля>",val);


Существует несколько freeware библиотек с более дружелюбным синтаксисом, но access там может и не поддерживаться. Например, http://soci.sourceforge.net/.
Кстати, если речь о визуальном представлении, то это совсем другая история...

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)