jkabbes
jkabbes

Reputation: 1

Having problems trying to connect to local SQL Server database in Visual Studio 2010 using C#

I'm having trouble trying to connect to a local database. I've tried some of the suggestions from other posts on this site but to no avail. Any help will be appreciated. Below is what I have so far.

private void button1_MouseClick(object sender, MouseEventArgs e)
{
    try
    {
        sConnection = "Server=(localdb)\Database1;Integrated Security=true;";

        dbConn = new SqlConnection(sConnection);
        dbConn.Open();

        sql = "SELECT * FROM Table2 ORDER" +
            "BY Customer name ASC;";
        dbCmd = new SqlCommand();
        dbCmd.CommandText = sql;
        dbCmd.Connection = dbConn;

        dbReader = dbCmd.ExecuteReader();

        while (dbReader.Read())
        {
            aMember = new member(dbReader["Name2"].ToString());
            this.listBox1.Items.Add(aMember);


        }

        dbReader.Close();
        dbConn.Close();
    }
    catch (System.Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

Upvotes: 0

Views: 902

Answers (3)

Brent
Brent

Reputation: 598

There are a couple of issues here that I can think of. I'll address two.

1. Connection String

You're wanting to connect to "Database1" as a Database and not an instance. Try changing your connection string first.
Change sConnection to this:
string sConnection = "Server=(localdb);Initial Catalog=Database1;Integrated Security=true;";

2. Using statement (Benefits of it...)


        var sConnection = "Server=(localdb);Initial Catalog=Database1;Integrated Security=true;";
        using (var sqlConn = new SqlConnection(sConnection))
        {
            sqlConn.Open();
            using (var cmd = sqlConn.CreateCommand())
            {
                cmd.CommandText = "SELECT * FROM Table2 ORDER BY [Customer Name]";

                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        aMember = new member(reader["Name2"].ToString());
                        this.listBox1.Items.Add(aMember); 
                    }
                }
            }
        }

Upvotes: 1

As marc_s mentioned: The correct connectionstring is "Server=(localdb)\v11.0;database=Database1;Integrated Security=true;"

Upvotes: 0

Praveen
Praveen

Reputation: 56501

I think here is the problem.

sConnection = "Server=(localdb)\Database1;Integrated Security=true;";

Check this

sConnection = "Server=(localdb)\\Database1;Integrated Security=true;";

Beginning in .NET Framework 4.5, you can also connect to a LocalDB database as follows:

server=(localdb)\\myInstance

Check this docs.

Upvotes: 0

Related Questions