Edward Kenway
Edward Kenway

Reputation: 9

C# insert in table doesn't work but select works perfect

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.

Upvotes: 0

Views: 1307

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500145

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.

Upvotes: 5

Hirav Sampat
Hirav Sampat

Reputation: 196

Check your query by running the same in sql server maybe the issue is you are writing the wrong table or column names somewhere And i guess as you are using ID column you must have kept is as identity If this is the case then you cannot insert a value t that column it'll take the value automatically..

Return your generated query in a label or something and check it in sql server if its working properly or not..

Upvotes: 0

Related Questions