C# Local Database – How to Connect and Use Local Database (Sql Server)

A local database is very essential for developing small
scale C# applications, because it doesn’t requires a server to store the data.
So this article is on how to connect and use C# local database.Well I am pretty sure that most of you would thing, what is
a Local Database? A local database is database which can be used locally on a computer, it doesn’t require a server. The advantage of using a local database is you can easily migrate your project from one computer to another (you don’t need to setup/configure a database server). Microsoft provides local database within visual studio which is often called as SQLCE (CE stands for compact
edition).

So let’s get started!

1. First of all create a new project in C# (make sure you
select the Netframe version above 3.5, because local database is supported in Netframe version 4.0 or above).

2. Now right click your project under solution explorer
-> select add new item.

3. A new window will be popped up, search for local database and add it.

4. Again a new window will be popped up which ask up to choose
a Database Model select Dataset and hit Next & hit Finish.

5. Now we have added a local database in our C# application.

6. Now we need to establish our connection between our local database & C# application.

7. So simply add a button from toolbox and change the text to Start Connection.

8. Double click your form and import the following:

using System.Data.SqlServerCe;

Note: If you are facing an error then watch the video tutorial.

9. Double click the button and add the following code:

SqlCeConnection Conn=new SqlCeConnection(//specify the connection string here)

10. In order to find the connection string, go to solution
explorer and open app.config file.

11. In the above screenshot you can see the connection string
just copy it and paste it here inside the brackets.

SqlCeConnection Conn=new SqlCeConnection(//specify the connection string here)

12. We are almost done now we just need to open the
connection so just double click the button and add the following code:

Conn.Open();
MessageBox.Show(“Connection Started”);

That’s it!! Hope you enjoyed the article, please do share
it!

Leave a Reply

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