0

i want to write data into a local database table. When i run the code there are no erros and when i count the rows after the insert statement the message box shows me that a row was inserted. But when i close the programm and look in my database there are no new rows.

I'm using C# and Visual Studio 2013.

Do anybody know what the problem is?

Thank you.

String connection = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Datenbank.mdf;Integrated Security=True;Connect Timeout=30";

            SqlConnection cnn = new SqlConnection(connection);
            cnn.Open();

            String query = "INSERT INTO Customer (ID, Name) VALUES (@id, @name)";
            SqlCommand command = new SqlCommand(query, cnn);

            command.Parameters.AddWithValue("@id", 1);
            command.Parameters.AddWithValue("@name", 'John');
            SqlDataReader reader;

            command.ExecuteNonQuery();

            query = "Select count(ID) from Customer";
            command = new SqlCommand(query, cnn);

            reader = command.ExecuteReader();

            while (reader.Read())
            {
                MessageBox.Show(reader[0].ToString());
            }

            reader.Close();
stutski
  • 5
  • 4
  • What does this return `command.ExecuteNonQuery();`? this should return 1 i.e. affected/inserted rows. – Nikhil Agrawal Jun 03 '15 at 18:11
  • You sure you're pointing to the right/same physical file (.mdf?) No chance of a duplicate/backup hanging around somewhere? Or default database not as expected? – David W Jun 03 '15 at 18:11
  • 1
    Probably is a duplicate [Why saving changes to a database fails?](http://stackoverflow.com/questions/17147249/why-saving-changes-to-a-database-fails/17147460#17147460) – Steve Jun 03 '15 at 18:15
  • command.ExecuteNonQuery(); return 1. I thin i have a duplicate or backup somewher but how do i solve this problem now? – stutski Jun 03 '15 at 19:36

1 Answers1

1

Try like this:

  try {
        int rowsAffected = command.ExecuteNonQuery();
        if (0 < rowsAffected) 
           MessageBox.Show("Success!");
        else 
           MessageBox.Show("Failed!");
    } catch (SqlException ex) {
       MessageBox.Show(ex.Message);
    } finally {
        if (cnn.State == ConnectionState.Open) 
           cnn.Close();
    }

Also refer: Why saving changes to a database fails?

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331