0

I'm trying to connect to a Microsoft Access database but i can't get the connection to work using c# to connect but can't get it to work trying to making a login form using sql connection, this is also a local connection

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection("Data Source ='(local)';Initial Catalog ='UserAccounts.accdb';Integrated Security=true");
    SqlDataReader rdr = null;
    try
    {
        conn.Open();
        MessageBox.Show("Working");
    }
    catch (Exception)
    {
        MessageBox.Show("Error with the databse connection");
    }
    finally
    {
        Console.ReadLine();
        if (rdr != null)
        {
            rdr.Close();
        }
        if (conn != null)
        {
            conn.Close();
        }
    }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
user2552211
  • 143
  • 1
  • 5
  • 14
  • 2
    If you do `catch (Exception exc) { MessageBox.Show(exc.Message); }` what helpful information does that provide? – Nathan Loding Jul 26 '13 at 00:02
  • @NathanLoding i get a network-related or instance-specific error occurred while establishing a connection to sql server. the server was not found or not accessible.Verify that the instance name is correct and that sql server is configured to allow remote connections.(provider : named pipes provider, error : 40 could not opne a connection to sql server) thats what it says i know i has to do with the way im calling it just not sure what ime doing wrong – user2552211 Jul 26 '13 at 00:09

2 Answers2

1

It may sound so simple, but you said you want to connect to MS Access, but are using SqlConnection, which is specifically to SQL Server, so of course it will never work.

For MS Access you can use OleDbConnection with a proper connection string, something like this:

private void button1_Click(object sender, EventArgs e)
{
    string connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserAccounts.accdb; Persist Security Info=False;";
    using(OleDbConnection conn = new OleDbConnection(connectionString))
    {
        try
        {
            conn.Open();
            MessageBox.Show("Working");
        }
        catch (Exception e)
        {
            MessageBox.Show("Error with the database connection\n\n + e.ToString()");
        }
    }
    Console.ReadKey(true);
}

Check the most appropriate connection string here

Alejandro
  • 7,290
  • 4
  • 34
  • 59
0

Your Data Source parameter is wrong, I think. Typically it's like Data Source=localhost\SQLEXPRESS if your SQL instance is named "SQLEXPRESS" on your local machine. Check out these links:

What is the sql connection string I need to use to access localhost\SQLEXPRESS with Windows Authentication or SQL Authentication?

http://www.connectionstrings.com/

Community
  • 1
  • 1
Nathan Loding
  • 3,185
  • 2
  • 37
  • 43