How to handle SQLite Unique Constraints error when the value already exists?

Have created a database and use unique constraints to avoid duplicate values. When I try to add a value that violates that rule, the app crashes.

How would you solve it? Should I first make a SQL query and see if the value already exists and if it doesn't exist add it? Does it feel a bit unnecessary to have two questions against the database, can I do it one query?

I want:

  1. Check if a value exists
  2. If it exist, give a message that it already exists
  3. If it doesn't exist add it How should I do it?

Using Nuget Package: System.Data.SQLiteLogin

C# Code

    // Connection String
    string DbFile = @"URI=file:Data\LearnWords.db";
    int status = 0;
    
    // Db Connection
    SQLiteConnection DbConnectiom = new SQLiteConnection(DbFile);
    DbConnectiom.Open();
    
    // SQL Command
    SQLiteCommand Cmd = new SQLiteCommand("INSERT INTO Word (WordClass, WordEng) VALUES('Test','Hello');", DbConnectiom);
    status = Cmd.ExecuteNonQuery();
    Console.WriteLine($"Status: {status}");
    
    DbConnectiom.Close();

Tried to find some documentation but couldn't find it



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation