C# – Connecting to SQL Server Express from Visual Studio

cdatabase-connectivitysql-server-2008sql-server-expressvisual studio 2010

I have SQL Server 2008 installed with Visual Studio 2010, I have downloaded a project which has database files created in Visual Studio project itself, now I want to connect to that database.

I tried changing the connection string but unable to connect to the database.

Can anyone tell me how to connect to the database, I have SQL Server 2008 (10.0.1600.22) installed on my machine

Updated connection string:

Here is the connection string I am using

Data Source=SQLEXPRESS\;Initial Catalog=INVENTORY;uid=xxx;pwd=xxx

where xxx\xxx is my machine and my installed SQL Server instance name respectively.

Best Answer

Are you using C#?

try this:

using namespace System.Data.SqlClient;

SqlConnection con = new SqlConnection("Data source = [ip]; Initial catalog = [db name]; User id = [user name]; password = [password]");

con.Open();

set a breakpoint at con.Open(), if it succeeds and passed this line, that means you have successfully connected to the database.

After that, you may want to execute a SQL Command try this:

    SqlCommand cmd = new SqlCommand("[command]", con);

        // if the command has no return value
        cmd.ExecuteNonQuery();
        //else you might want a Sql data reader to read the return value
        SqlDataReader read = cmd.ExecuteReader();
        while(read.Read())
    {
//do something
    }