0

I am developing a Winforms application in which I am using SQL Server 2008 Express Edition as backend. But I am getting error:

Additional information: An attempt to attach an auto-named database for file D:\Hardik\Hardik\dotnet\TestApplication\TestApplication\bin\Debug\MyDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

My code is:

private void Form1_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "Select * From MyTable";
    cmd.CommandType = CommandType.Text;

    da = new SqlDataAdapter();
    da.SelectCommand = cmd;

    dt = new DataTable();
    ds = new DataSet();

    da.Fill(ds, "Login");
    dt = ds.Tables[0];

    dataGridView1.DataSource = dt;
}

and my app.config file is:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <connectionStrings>
       <add name="MyConnection" 
            connectionString="Server=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True; User Instance=True" 
            providerName="System.Data.Client"/>
   </connectionStrings>
</configuration>

Where I am wrong?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ubiquitous Developers
  • 3,637
  • 6
  • 33
  • 78
  • `AttachDbFilename` - this is used rather for LocalDB I would say. For SQL Express you usually keep your database attached and do not detach it after your app is finished. – Vojtěch Dohnal Sep 28 '14 at 11:28

1 Answers1

0

use double slash instend of single slash.

A UNC path uses double slashes or backslashes to precede the name of the computer.

<connectionStrings>
    <add name="MyConnection" connectionString="Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True; User Instance=True" providerName="System.Data.Client"/>
  </connectionStrings>

for instance failure As you got the error "instance failure", that might be the error with your SQL Server instance..

Make sure your SQL Server instance(MSSQLSERVER) is running, where you can check in: Services list. TO get into services list: open run dialog box and type: "services.msc" (without quotes) and hit Enter. That takes you to services management console, where you can check whether your instance in running or not..

If the problem still persists, then try using: Data Source=.\SQLEXPRESS instead.. :)

MMM
  • 3,132
  • 3
  • 20
  • 32