I work at a Windows Form C# application but i have some troubles. When I want to select from table everything works perfect ,but when i want to insert data in my table have not error and my application says "The data was inserted in database", but my table is empty.
This is my connection :
SqlConnection conexiune = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Baza-de-date.mdf;Integrated Security=True");
This is my code:
try
{
SqlCommand insert = new SqlCommand("INSERT INTO [dbo].[Tabel] ([ID], [Nume], [Prenume], [Varsta]) VALUES (@id, @nume,@prenume,@varsta)", conexiune);
insert.Parameters.AddWithValue("@id",textBox1.Text);
insert.Parameters.AddWithValue("@nume", textBox2.Text);
insert.Parameters.AddWithValue("@prenume", textBox3.Text);
insert.Parameters.AddWithValue("@varsta", textBox4.Text);
conexiune.Open();
insert.ExecuteReader();
MessageBox.Show("Datele au fost introduse cu succes in baza de date!", "Succes!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("A avut loc o eroare! Te rog sa incerci din nou", "Eroare!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
conexiune.Close();
this.Close();
}
I'm using Visual studio 2013 and Microsoft SQL Server version 11.00.3000.
This is a problem, at least:
insert.ExecuteReader();
That's meant for queries, because you're reading data. (As noted by Steve, it would still work - but it's not
Call ExecuteNonQuery
instead:
insert.ExecuteNonQuery();
Additionally, I'd advise using using
statements instead of manually closing resources. (You should close the SqlCommand
too.)
However, the real problem was found by Steve in comments - you were copying a fresh copy of the database on each run. So I'd expect you to see the results of the insert within one execution of the application, but they'd be lost next time you started the app.
See more on this question at Stackoverflow