user990692
user990692

Reputation: 543

I can't connect to my local SQL Server database

I'm currently learning ADO.NET on C#. I'm learning by a book and tutorials that I found online. I wanted to try some of the samples to get myself familiarized with the whole SQL connnection and command objects and so on. Hence, I tried this:

namespace ConsoleApplication
{
    class SqlDemo
    {
        public void InitConnection ()
        {
            string connString = @"data source=C:\SQL Server 2000 Sample Databases; database=northwnd; integrated security=SSPI";
            SqlConnection conn = null;

            try
            {
                conn = new SqlConnection (connString);
                conn.Open ();
                Console.WriteLine ("DataBase connection established");
            }
            catch
            {
                Console.WriteLine ("DataBase connection not established");
            }
            finally
            {
                if (conn != null) conn.Close ();
            }

            Console.ReadKey (true);
        }

        static void Main (string[] args)
        {
            SqlDemo d = new SqlDemo ();
            d.InitConnection ();
        }
    }
}

And no matter how I try, I can connect to the local database. "data source=(local)" don't work.

Upvotes: 0

Views: 2505

Answers (3)

Isuru
Isuru

Reputation: 31283

If you are using SQL Server 2000, then just put 'local' or simply '.' (exclude the quotes) for the data source. And you have a typo in the database name. It should be 'Northwind'

Upvotes: 0

Steve Wellens
Steve Wellens

Reputation: 20620

If you wish to connect to a database file using a path:

Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

From: http://www.connectionstrings.com/sql-server-2008

However, you may also need to "Attach" the database to Sql Server. In Management studio, right click the Databases folder and select "Attach..."

Upvotes: 0

competent_tech
competent_tech

Reputation: 44921

A couple of things:

1) It looks like you may have a typo in your database name. It should probably be:

database=northwind

2) Your data source should be (local) or . OR you may have an instance installed, in which case you may need to include the instance name as well, such as .\SQLExpress or .\SQLServer.

Upvotes: 3

Related Questions