I tried this c# update if record exists else insert new record to update my table, if records exists.
But I run into the exception: "Violation of Primary Key constraint". Because of this line cmdCount.Parameters.AddWithValue("@local_programs_id", local_programs_id);
and because there's already a value for local_programs_id
in the table
What have I done wrong?
Thanks a lot.
SqlConnection connection = new SqlConnection(sqlConnection_String);
SqlCommand cmdCount = new SqlCommand("SELECT count(*) FROM " + datenbankname + " WHERE local_programs_id = @local_programs_id" , connection);
cmdCount.Parameters.AddWithValue("@local_programs_id", local_programs_id);
connection.Open();
int count = (int)cmdCount.ExecuteScalar();
Console.WriteLine("count1 " + count);
if (count > 0)
{
SqlCommand updateCommand = new SqlCommand("UPDATE " + datenbankname +
" SET local_programs_Id = @local_programs_Id, " +
"program_name = @program_name, " +
"publisher_name = @publisher_name, " +
"program_version = @program_version, " +
"install_dir = @install_dir, " +
"uninstall_dir = @uninstall_dir, " +
"inserted_at = @inserted_at, " +
"direct_link_available = @direct_link_available", connection);
updateCommand.Parameters.AddWithValue("@local_programs_Id", local_programs_id);
updateCommand.Parameters.AddWithValue("@program_name", program_names);
updateCommand.Parameters.AddWithValue("@publisher_name", publisher_names);
updateCommand.Parameters.AddWithValue("@program_version", program_version);
updateCommand.Parameters.AddWithValue("@install_dir", install_location);
updateCommand.Parameters.AddWithValue("@uninstall_dir", uninstall_location);
updateCommand.Parameters.AddWithValue("@inserted_at", DateTime.Now);
updateCommand.Parameters.AddWithValue("@direct_link_available", direct_link_available);
int rowsUpdated = updateCommand.ExecuteNonQuery();
Console.WriteLine("rowsUpdated " + rowsUpdated);
}
else
{
Console.WriteLine("inserted1 ");
string query = "INSERT INTO " + datenbankname + " (local_programs_Id, program_name, publisher_name, program_version, install_dir, uninstall_dir, inserted_at)";
query += " VALUES (@local_programs_Id, @program_name, @publisher_name, @program_version, @install_dir, @uninstall_dir, @inserted_at)";
SqlCommand insertCommand = new SqlCommand(query, connection);
insertCommand.Parameters.AddWithValue("@local_programs_Id", local_programs_id);
insertCommand.Parameters.AddWithValue("@program_name", program_names);
insertCommand.Parameters.AddWithValue("@publisher_name", publisher_names);
insertCommand.Parameters.AddWithValue("@program_version", program_version);
insertCommand.Parameters.AddWithValue("@install_dir", install_location);
insertCommand.Parameters.AddWithValue("@uninstall_dir", uninstall_location);
insertCommand.Parameters.AddWithValue("@inserted_at", DateTime.Now);
int rowsInserted = insertCommand.ExecuteNonQuery();
}