Search code examples
c#.netms-access-2016

Error when trying to connect to access database in C# for project


I am trying to create a project that will read, write,and check for duplicates in my access data base file. I am using C# and keep getting "Connection failed error that I have written into the program if the connection state = 0. If anyone can offer any help I would appreciate it. I am using Access 2016 and I am not sure what references I need for my project (if any). Everything I have found online is either outdated or doesn't work.

Thank you!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.IO;
using System.Data.OleDb;


 namespace RHG
{

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

        using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\grosales\Documents\rhg\RHG\Used.accdb"))
        {
            try
            {
                connection.Open();
                MessageBox.Show("connected");
            }
            catch (Exception ex)
            {
                MessageBox.Show("connection failed");
            }
        }

    }

`


Solution

  • You have not opened the connection.

    connection.Open();
    

    Note: Checking the connection state is not enough. You might get an exception when trying to open the connection. Enclose it in try-catch instead.

    It is also a good practice to enclose work on a connection with using

    using (var connection = new OleDbConnection()) {
        connection.ConnectionString =
            @"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\...\Used.accdb";
        try {
            connection.Open();
    
            //TODO: do something with the connection
    
        } catch (Exception ex) {
            MessageBox.Show("Connection Failed\r\n\r\n" + ex.Message);
        }
    }
    

    This ensures that the connection will be closed and the resources be released.