Connecting to SQL Server database using Visual C++

ankit0311 picture ankit0311 · Feb 25, 2012 · Viewed 13.3k times · Source

I am trying to connect to the sample database Northwind in SQL Server 2005 Express through Visual C++ 2008 using the following code:

SqlConnection^ con=gcnew SqlConnection();
con->ConnectionString="Data Source=localhost\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI";

SqlCommand^ com=gcnew SqlCommand();
com->Connection=con;
com->CommandText="Select * From Customers";

try
{
    con->Open();

    SqlDataReader^ myReader;
    myReader=com->ExecuteReader();
    myReader->Read();

    Console::WriteLine(myReader->GetData(5));

    myReader->Close();
}
catch(Exception^ e)
{
    Console::WriteLine(e->Message);
}
finally
{
    con->Close();
}

But I am getting the exception that

login to the database failed for the user PC-ANKIT

And after this, I have no idea what happens, but the the tables in the database magically disappear. The list of databases in the SQL Server Management Studio still shows the Northwind database, but it does not contain any tables, views or anything.

Also, when I try doing the same thing using an equivalent code in VB in Visual Web Developer 2008 express edition - no problem arises whatsoever! I am able to connect to the database and access the data in all the tables.

Can anyone please help me resolve this problem? Thanks in advance!

Answer

TCS picture TCS · Feb 25, 2012

Try connecting to the database using visual studio's server explorer. If you connect successfully, you can right-click the connection and check out the properties. In there you will find the connection string - use that in your application and check out if it works.

Notice that this is a trusted connection, if you want to use username and password I use:

Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Integrated Security=SSPI;

Hope it helps!