Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

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

newSqlConnection(@"C:\Users\...")

Solution 3:

For path you can't add backslashes just like that . You need to escape backslashes . There are two ways

to escape backslash

Method #1 - Use @ in the beginning of the path string

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

Method #2 - add double backslashes instead of one backslashes

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

Solution 4:

SqlConnection con = new SqlConnection(@"C:\Users\Documents\Visual Studio
    2012\Projects\DataBaseTest\MyDatabase#1.sdf");

Solution 5:

You need to use the @ symbol to show that the string is literal, and ignore special characters.

This page shows samples http://www.dotnetperls.com/string-literal

Post a Comment for "C# Database Connection String"