Stop Having Multiple Connection Strings in C#
Table of contents
Introduction
In this article, I will discuss how you can query/access your SQL database from multiple files in a C# project by only using one connection string instead of many.
Problem Statements
If you are making a large full-stack project in C# and you are a beginner then it is likely that you have multiple connection strings in different files of your project. This is a problem because as developers we should follow DRY principles (don't repeat yourself) and make code maintainable. This can become a bigger problem if you're working in a team because each teammate will need to change multiple connection strings to run the project locally and this can potentially lead to other issues later on like merge conflicts etc.
My Own project
In my project which is a Task Application made using C#, Windows Forms, .NET Framework and SQLite, I created multiple connection strings as you can see below:
When I relocated my project to a different PC I had to go through this project and change each connection string to the new file path of the SQLite database which was quite tedious and frustrating.
Solution
In order to solve this issue I created a file in my project called DB.cs
:
Inside this file I created a public class
with a public static string
variable called DBLocation
which is where our database path will be stored. By setting the class and string as public
we can access the variable DBLocation
in other files of our project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TASK_APP
{
public class DB
{
public static string DBLocation = @"data source = add your path here";
}
}
Now that I have done this I can get rid of the connection strings in my other files and replace them with DBLocation
:
Congrats you have now set up the connection 🥳.
Subscribe to my newsletter
Read articles from Noor Ahmed directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Noor Ahmed
Noor Ahmed
I am a software engineer intern from the UK and I have worked with multiple technologies like MERN stack, JavaScript, Python etc. I also like to contribute to open source on Github.