Note that there are some explanatory texts on larger screens.

plurals
  1. POSQLite and Javascript : Checking for existence of data before inserting OR letting SQLite throw an exception
    text
    copied!<p>My primary question is which approach is faster.</p> <p><strong>Some briefing</strong> </p> <p>I'm developing an application using Mozilla.</p> <p>I have this one module where I capture some data and store it in database. The data comes in intermittently. No duplicates are to be stored. For discussion sake we can assume a table with just one column, and let's name that column is named 'keyword'. So if we get a keyword that's already in database we do not store it again. And yes, we have set this column as PRIMARY KEY and made it UNIQUE. :)</p> <p><strong>The query I have is:</strong></p> <p>1) Before I insert this new data into the database, shall I do a DB call and check if the keyword exists or not; if it doesn't exists put it into DB? Something like:</p> <pre><code>function insert_keyword(keyword) { if(!SQL.exists(keyword)) { SQL.insert(keyword); } } </code></pre> <p>OR</p> <p>2) I just insert and let the database handle the condition, effectively letting it throw an exception, which I catch.</p> <pre><code>function insert_keyword(keyword) { try { SQL.insert(keyword); } catch (e) { // keyword exists! } } </code></pre> <p>I know catching an exception and not doing anything is bad! So I'm not looking for what is good and what is bad :) . What I want to understand is which approach would be the fastest. (Specifically in relation to Mozilla, JavaScript and SQLite but general comments are welcomed!)</p> <p><strong>Sidenotes:</strong> <em>The <strong>SQL.</strong> syntax I've used is just for illustration purpose. You may assume that I create SQL statements, execute them and fetch the result, or assume it is a JavaScript library call which does all the dirty work.</em></p> <p><strong>This question is a bit like this one:</strong></p> <p><a href="https://stackoverflow.com/questions/405359/should-i-check-for-db-constraints-in-code-or-should-i-catch-exceptions-thrown-by">Should I check for DB constraints in code or should I catch exceptions thrown by DB</a></p> <p>But I want to understand the performance related differences specifically, as the application I'm working on needs to be as fast as possible (which application doesn't? ;) )</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload