I am getting an error whenever I am saving the data to the SQL Server database using C#

-4

I am working with my personal project which is a personal expenses system. I am trying to save data to SQL Server, but I am always getting an error:

"0x80131904" an attempt to attach an auto name database. A database with the same name exists. or specified file cannot be opened or it is located on UNC share"

To give you the complete error I attached here.

Thanks.

try
{ 
    SqlConnection conn =  new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\Francis\source\repos\Personal Expenses System\NumData.mdf;Integrated Security=True;Connect Timeout=30");

    conn.Open();

    string insert_query = "INSERT INTO [Table111] (House Rent, NB Power, Car Insurance, Life Insurance, Gasoline, Grocery, Rogers Internet, kodoo Mobile, Laundry, Tithes, Padala, Extra, Total, Gross Income, Net Income) VALUES (@House Rent, @NB Power, @Car Insurance, @Life Insurance, @Gasoline, @Grocery, @Rogers Internet, @kodoo Mobile, @Laundry, @Tithes, @Padala, @Extra, @Total, @Gross Income, @Net Income)";

    SqlCommand cmd = new SqlCommand(insert_query, conn);

    cmd.Parameters.AddWithValue("@House Rent", textbox1.Text);
    cmd.Parameters.AddWithValue("@NB Power", textBox2.Text);
    cmd.Parameters.AddWithValue("@Car Insurance", textBox3.Text);
    cmd.Parameters.AddWithValue("@Life Insurance", textBox4.Text);
    cmd.Parameters.AddWithValue("@Gasoline", textBox5.Text);
    cmd.Parameters.AddWithValue("@Grocery", textBox6.Text);
    cmd.Parameters.AddWithValue("@Rogers Internet", textBox7.Text);
    cmd.Parameters.AddWithValue("@kodoo Mobile", textBox8.Text);
    cmd.Parameters.AddWithValue("@Laundry", textBox9.Text);
    cmd.Parameters.AddWithValue("@Tithes", textBox10.Text);
    cmd.Parameters.AddWithValue("@Padala", textBox11.Text);
    cmd.Parameters.AddWithValue("@Extra", textBox12.Text);
    cmd.Parameters.AddWithValue("@Total", textBox13.Text);
    cmd.Parameters.AddWithValue("@Gross Income", textBox14.Text);
    cmd.Parameters.AddWithValue("@Net Income", textBox15.Text);

    cmd.ExecuteNonQuery();

    MessageBox.Show("Record SAVE");
    conn.Close();
}
catch (Exception ex)
{
    MessageBox.Show("EROR:" + ex.ToString());
}

I attached the screen shot of the error. It was lengthy one.

ERROR SQL

c#
sql
asked on Stack Overflow Jan 3, 2019 by Francis Naval • edited Jan 3, 2019 by marc_s

1 Answer

0

The problem is probably happening because you're not defining a correct path for your database file NumData.mdf. Using your error message "an attempt to attach an auto named database for file" I found this answer here:)

answered on Stack Overflow Jan 3, 2019 by mourato • edited Jan 3, 2019 by mourato

User contributions licensed under CC BY-SA 3.0