Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7084257
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T07:16:44+00:00 2026-05-28T07:16:44+00:00

My C++ code successfully restores an SqlServer database backup file and then extracts the

  • 0

My C++ code successfully restores an SqlServer database backup file and then extracts the necessary information from the resulting database using the OLEDB API.

Here is my C++ code, in the end of which I get an IDBCreateCommand instance ready to be used for executing various queries against the restored database:

DB::DB(LPCWSTR wszDataSource, LPCWSTR wszBackupFilePath, LPCWSTR wszRestoreFolderPath)
{
  fs::path backupFilePath = fs::canonical(wszBackupFilePath).make_preferred();
  fs::path restoreFolderPath = fs::canonical(wszRestoreFolderPath).make_preferred();
  std::wstring db = backupFilePath.leaf().stem().wstring();
  boost::wformat restoreQueryFmt(L"RESTORE DATABASE [%2%] FROM DISK = N'%1%' WITH REPLACE, STATS = 10, MOVE N'%2%' TO N'%3%\\%2%.mdf', MOVE N'%2%_log' TO N'%3%\\%2%.LDF'");
  std::wstring query = (restoreQueryFmt % backupFilePath.wstring() % db % restoreFolderPath.wstring()).str();

  IDBInitializePtr spDBInitialize;
  HRESULT hr = spDBInitialize.CreateInstance(CLSID_SQLNCLI10, NULL);
  if (REGDB_E_CLASSNOTREG == hr)
  {
    hr = spDBInitialize.CreateInstance(CLSID_SQLNCLI, NULL);
  }
  _HRESULT_CHECK3(spDBInitialize, hr);

  _variant_t vDataSource(wszDataSource);
  _variant_t vAuth(L"SSPI");

  DBPROP dbprop[2];          // property used in property set to initialize provider

  dbprop[0].dwPropertyID = DBPROP_INIT_DATASOURCE;
  dbprop[0].dwOptions  = DBPROPOPTIONS_REQUIRED;
  dbprop[0].vValue = vDataSource;

  dbprop[1].dwPropertyID  = DBPROP_AUTH_INTEGRATED;
  dbprop[1].dwOptions = DBPROPOPTIONS_REQUIRED;
  dbprop[1].vValue = vAuth;

  DBPROPSET dbpropset[1];        // Property Set used to initialize provider
  dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
  dbpropset[0].rgProperties  = dbprop;
  dbpropset[0].cProperties = sizeof(dbprop)/sizeof(dbprop[0]);

   // Set initialization properties.
  IDBPropertiesPtr spDBProperties = spDBInitialize;

  _HRESULT_CHECK(spDBProperties, SetProperties(1, dbpropset));
  _HRESULT_CHECK(spDBInitialize, Initialize());

  IDBCreateSessionPtr spCreateSession = spDBInitialize;
  _HRESULT_CHECK(spCreateSession, CreateSession(NULL, IID_IDBCreateCommand, reinterpret_cast<IUnknown **>(&m_spDBCreateCommand)));

  ICommandTextPtr spCommandText;
  _HRESULT_CHECK(m_spDBCreateCommand, CreateCommand(NULL, IID_ICommandText, reinterpret_cast<IUnknown **>(&spCommandText)));

  _HRESULT_CHECK(spCommandText, SetCommandText(DBGUID_SQL, query.c_str()));
  _HRESULT_CHECK(spCommandText, Execute(NULL, IID_NULL, NULL, NULL, NULL));
  _HRESULT_CHECK(spCommandText, SetCommandText(DBGUID_SQL, (boost::wformat(L"USE \"%1%\"") % db).str().c_str()));
  _HRESULT_CHECK(spCommandText, Execute(NULL, IID_NULL, NULL, NULL, NULL));
}

What it does is:

  1. Initializes a new database connection using the given data source (like “.\SQLEXPRESS”) and SSPI integrated authentication scheme.
  2. Executes a RESTORE DATABASE T-SQL statement, like this one: RESTORE DATABASE [my_db] FROM DISK = N'c:\temp\my_db.ebf' WITH REPLACE, STATS = 10, MOVE 'my_db' TO N'c:\temp\my_db.mdf', MOVE N'my_db_log' TO N'c:\temp\my_db.LDF'
  3. Use the new database for the subsequent queries by running USE "my_db"

So, I have no problems restoring a database backup file and proceding from there.

Now I am facing another problem. Suppose there is no backup file, rather an already existing MDF file – how do I attach to it using the OLEDB C++ API?

Thanks.

EDIT

It is assumed that the .mdf file is accompanied by all the files required by the database engine – .ldf and others as needed.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T07:16:45+00:00Added an answer on May 28, 2026 at 7:16 am

    You cannot attach a database if all you have is and MDF file because that is, at best, only half of the database. You need an MD and an LDF. And any additional NDF or secondary LDF files that composed the original database.

    Suppose you have the MDF and the LDF as %1% and %3%, then all you have to do is execute this statement:

    CREATE DATABASE [%2%] 
      ON (FILENAME=N'%1%')
      , (FILENAME=N'%3')
      FOR ATTACH;
    

    See How to: Move a Database Using Detach and Attach (Transact-SQL)

    The option to attach and MDF alone does exists (use FOR ATTACH_REBUILD_LOG) but it comes with many warnings, as it only works on a cleanly shut down database (it can lead to a corrupted database otherwise). There is no option to attach a database if you’re missing secondary NDF files.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Has anybody ever successfully written code to extract data from a SharePoint 2007 list
I am successfully instantiating/automating Visual Studio using the following code: System.Type t = System.Type.GetTypeFromProgID(VisualStudio.DTE.9.0);
using the Code Snippet for sending email in VB.Net I have successfully sent an
Code successfully upload file when I remove jquery script codes and submit. But with
The following hpricot code successfully extracts the STPeriods in the XML on two of
So when I try this code (one line at a time): BACKUP DATABASE [test]
I'm using below code to publish a flv file on Facebook wall. $description=$imgdetails; $href=http://www.abc.net;
I first retrieve information from the SQLite database into a cursor. The cursor contains
On a Vista dev machine I used this code successfully to change user Administrator
I've written the following code to (successfully) connect to a socks5 proxy. I send

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.