Loplac92 Loplac92 - 2 months ago 16
SQL Question

Cannot save information to database - UNC share issue?

I'm attempting to save information to a local sqldatabase I've created to accept loss events for a process. However my issue at the moment is not an error message with regards to the code, but regarding the database itself I think. The error message box says, "An attempt to attach an auto-named database for file C: [Database file location] failed. A database with the same name exists, or specified file cannot be opened, or it is located in a UNC share."
I have looked else where but nothing directly relates to my issue/or has worked.
Pulling my hair out now! Thanks in advance.

My code is:

private void button1_Click(object sender, EventArgs e)
{

string constring = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=c: \\users\\user\\documents\\visual studio 2015\\Projects\\LossApplication\\LossApplication\\LossDB.mdf;Integrated Security=True; ";

string query=" insert into LossDB.LossTable (lossid,Equipment, Event, responsinility, start) values(@lossid, @equipment, @Cause, @reason, @start) ;";

SqlConnection conLossDB = new SqlConnection(constring);
SqlCommand cmdLossDB = new SqlCommand(query, conLossDB);
cmdLossDB.Parameters.AddWithValue("@lossid", textBox1.Text);
cmdLossDB.Parameters.AddWithValue("@Equipment", comboBox1.Text);
cmdLossDB.Parameters.AddWithValue("@Cause", comboBox2.Text);
cmdLossDB.Parameters.AddWithValue("@Reason", comboBox3.Text);
cmdLossDB.Parameters.AddWithValue("@start", dateTimePicker1.Text);

SqlDataReader myReader;
try
{
conLossDB.Open();
myReader = cmdLossDB.ExecuteReader();
MessageBox.Show("Loss Entry Saved");
conLossDB.Close();
while (myReader.Read())
{

}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

K.K K.K
Answer

In your connection String,Use Initial catalog instead of AttachDbFilename

string constring = "Data Source=(LocalDB)\MSSQLLocalDB;
Initial Catalog = c: \users\user\documents\visual studio 2015\Projects\LossApplication\LossApplication\LossDB.mdf;
Integrated Security=True; ";

Even i faced this issue,above code resolves.