stutski
stutski

Reputation: 3

Cannot insert the data into the table C# visual studio 2013

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();

Upvotes: 0

Views: 1117

Answers (1)

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

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?

Upvotes: 1

Related Questions