Quering and Adding Info To Access Database Using C#

In this post, I will show you how I created a program to extract and add data to an Access database. Before we get started, you can see my current specifications below:

Getting values from a table:

Using System.Data.OleDB;

//Create a new list to hold all the values
List<String> values = new List<String>();

//Build the connection string and SQL string
string connectionString = @$"Provider=Microsoft.ACE.OLEDB;Data Source = C:\Path\To\Access.accdb";
string sqlString = "SELECT * FROM Table_Name";

//Create a new connection to the Access file
using (OleDbConnection connection = new OleDbConnection(connectionString)){

    //Creating a new command
    OleDbCommand command = new OleDbCommand(sqlString, connection);
    
    //Try/catch to catch errors, DON'T DO THIS IN SERIOUS PROJECTS!
    try{
        
        //Opening the connection and reading the data
        connection.Open();
        using(OleDbDataReader reader = command.ExecuteReader()){
            while(reader.Read()){
                
                //Adding the value to the values list
                values.Add(reader["Field_Name"].ToString());
            }
        }
    }catch{ }
    
    //Closing the connection
    connection.Close();
}

//Sorting the list in ascending order
values.Sort();

 

Adding a new row to the table:

Using System.Data.OleDb;

//Building the connection string and SQL string
string connectionString = @$"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Path\To\Access.accdb";
string sqlString = $"INSERT INTO Table_Name(Field_Name1, Field_Name2) VALUES ('{Field_Value1}','{Field_Value2}')";

//Creating a new connection to the Access file
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
    //Build a new command
    using(OleDbCommand command = new OleDbCommand(sqlString, connection))
    {
        //Open the database connection and execute the write
        connection.Open();
        command.ExecuteReader();
    }
    //Close the database connection
    connection.Close();
}

Enjoy!

Leave a Comment

Your email address will not be published. Required fields are marked *

email popup image
Mark Harwood
NEVER miss a blog post again! Subscribe for email notifications whenever a new post is live!
Subscribe
NEVER miss a blog post again! Subscribe for email notifications whenever a new post is live!
Fill Out This Form, And I Will Be In Touch Shortly
Contact form image
I'll Be In Touch Soon