Search code examples
visual-c++sql-server-expressvisual-studio-express

Minimal code to connect to MSSQL Server Express and extract some table data using Visual C++ Express


I have the following software installed on the machine:

  • Microsoft SQL Server Express 2005
  • Microsoft Visual C++ Express 2008

I have a .mdf file from which I need to read some data and dump to a text file. I can browse the database file using the Database Explorer in Visual Studio without any problem, but I'm having trouble connecting from the application.

I googled far and wide, almost all "solutions" say that I should start a new project and select the "SQL server application template", which I don't have amongst templates. Other tutorials I found say I should use "Data Source Configuration Wizard", however I cannot find such wizard in any of the menus.

I don't mind clicking although I would prefer if all this was doable in plain C++ code. Something like:

DbConnection *d = new MSSQLConnection("local", "c:\path\to\file.mdf");
DbQuery *q = new DbQuery(d, "select * from mytable");
...dump the data and go home

Thanks.

Alternatively, if someone can tell me how to do this in C++:

http://sharpertutorials.com/connecting-to-a-sql-server-database/


Solution

  • And here it is. Quite simple and easy once you know it...

    SqlConnection^ myConnection = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=\"file.mdf\";Integrated Security=True;Connect Timeout=10;User Instance=True");
    myConnection->Open();
    
    SqlCommand^ scmd = gcnew SqlCommand("select ID from atable", myConnection);
    SqlDataReader^ r = scmd->ExecuteReader();
    while (r->Read())
        __int64 id = r->GetInt64(0);
    r->Close();