Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# database connection string

I'm fairly new to c# and just now started working with databases. I made a local database in my project folder, when I click properties on the database I get "Connection string" as:

Data Source="C:\Users\Documents\Visual Studio 2012\Projects\DataBaseTest\MyDatabase#1.sdf"

My question is simple, how do I create a connection string using that line? cause writing this generates an error for some reason.

SqlConnection con = new SqlConnection(Data Source="C:\Users\Documents\Visual Studio
    2012\Projects\DataBaseTest\MyDatabase#1.sdf");
like image 929
Jacco Avatar asked Jan 31 '26 08:01

Jacco


2 Answers

You are using a SQL Server Compact edition database and for that you must use SqlCeConnection instead of SqlConnection (Which is used for SQL Server).

You must also escape the back backslashes in your connection string \ becomes this \\ :

SqlCeConnection sqlConnection = new SqlCeConnection("Data Source=C:\\Users\\Documents\\Visual Studio
2012\\Projects\\DataBaseTest\\MyDatabase#1.sdf");

or use a verbatim string :

SqlCeConnection sqlConnection = new SqlCeConnection(@"Data Source=C:\Users\Documents\Visual Studio
2012\Projects\DataBaseTest\MyDatabase#1.sdf");

And if you don't have the necessary libs for using SqlCe in your projects refer to my other answer here :

Download the libs from here Microsoft SQL Server Compact 4.0

  1. Add a reference to System.Data.SqlServerCe.dll to your project
  2. Add this using directive using System.Data.SqlServerCe;
  3. Use SqlCeConnection instead of SqlConnection
like image 154
Nasreddine Avatar answered Feb 01 '26 20:02

Nasreddine


You need to escape backslashes (replace backslashes by double backslashes) or put an @ in front of your string to tell C# to take it literally, like so:

new SqlConnection("C:\\Users\\...")

or

new SqlConnection(@"C:\Users\...")
like image 20
Roy Dictus Avatar answered Feb 01 '26 21:02

Roy Dictus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!