I am trying to create a new record in the database, but I don’t have one. For adding used earlier INSERT into... , record was added, but was not saved. Read what you need to use to save UPDATE but now the record is not added at all. Maybe they need to be used together?

 string connStr = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\LitMapPoltavaData.mdf;Integrated Security=True"; SqlConnection conn = new SqlConnection(connStr); try { //пробуем подключится conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Parameters.Clear(); cmd.Connection = conn; cmd.CommandText = "UPDATE Writers SET Id = @Id, Surname = @Surname, Name = @Name, Lived = @Lived, Birthplace = @Birthplace, ShortInfo = @ShortInfo WHERE Id = @Id"; // Добавить параметры cmd.Parameters.AddWithValue("@Id", tag); cmd.Parameters.AddWithValue("@Surname", tbSurname.Text); cmd.Parameters.AddWithValue("@Name", tbName.Text); cmd.Parameters.AddWithValue("@Lived", tbLived.Text); cmd.Parameters.AddWithValue("@Birthplace", tbBirthplace.Text); cmd.Parameters.AddWithValue("@ShortInfo", tbShortInfo.Text); //Выполнить cmd.ExecuteNonQuery(); } finally { conn.Close(); conn.Dispose(); } 
  • update only changes existing entries, and insert only inserts new ones. yes, use both depending on what you need at the moment - Mike
  • use commit; to save commit; - Denis
  • @Mike can write how to combine them? - Vyacheslav
  • There are three ways: 1. you have already written in the answer, give update, check the number of updated records. 2. Do an insert - if a duplicate entry error is returned - do an update. 3. By some criteria you give to the database select count (*) to determine the presence of the record and if it is there give the update - Mike

1 answer 1

how to combine them

 cmd.CommandText = "UPDATE Writers ..."; ... int recordsAffected = cmd.ExecuteNonQuery(); if (recordsAffected == 0) { cmd.CommandText = "INSERT INTO Writers ..."; ... cmd.ExecuteNonQuery(); } 
  • Many thanks! - Vyacheslav