0

I have created a LocalDB database in my project and its connection string is :

Data Source=(LocalDB)\v11.0;AttachDbFilename="E:\Projects\visual studio 2013\Projects\sqlce\mydb.mdf";Integrated Security=True;Connect Timeout=30

How should I pass it to SqlConnection()?

Note that it has an address within quotation marks. Have I done anything wrong?

I guess even if I program it correctly it won't work in another computer which doesn't have that .mdf file in that exact place. Isn't it so?

How can I have a program with a portable database so I can easily publish my pp?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Geekmard
  • 166
  • 1
  • 3
  • 10
  • Put your connection string in app.config--related question http://stackoverflow.com/questions/14918912/app-config-connection-string -- or escape your quotes -- http://stackoverflow.com/questions/25072580/how-can-i-escape-quotes-within-a-string-that-is-stored-in-a-variable-in-c-sharp –  Mar 29 '15 at 18:39
  • SQL Server (which is what uses the `.mdf` file) is a **server-based** database system - it can definitely not be considered a *portable* database. You need to either **install** SQL Server (the core engine) on a remote system, or have access to a LAN with a SQL Server instance running somewhere on that LAN... – marc_s Mar 29 '15 at 18:56

2 Answers2

0

Add the mdf file to your solution and and change the property "Copy to Output Directory" to Copy Always. Don't hardcode the mdf file path in connection string. Add the connection string in app.config or web.config file like below:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\myDB.mdf;Initial Catalog=MyDatabaseName;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

Then you can access the connection string in your C# code as below:

string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()

If you face any error regarding accessing the mdf file, the you can set the DataDirectory in your C# code using AppDomain.CurrentDomain.SetData() method.

skjcyber
  • 5,759
  • 12
  • 40
  • 60
0
<connectionStrings>
  <add 
    name="NorthwindConnectionString" 
    connectionString="Data Source=serverName;Initial 
    Catalog=Northwind;Persist Security Info=True;User 
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>

you can access by

connString =rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];

More about connection string

SqlConnection con = new SqlConnection(connstring);

or you can go in this way like

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MMM
  • 3,132
  • 3
  • 20
  • 32