Reputation: 57
How can I only add a new user if it doesn't already exist?
Here is how I'm currently inserting a new user into the database
assert(typeof details.username === 'string');
db.execute("INSERT INTO user (??) VALUES (?)",
[
['username'],
[details.username]
Upvotes: 0
Views: 63
Reputation: 7872
Just alter your column set UNIQUE
attribute.
Well, it sounds like you only have one column in your table.
So, if you want a value to be inserted one your column must be set as UNIQUE
.
See : http://technet.microsoft.com/en-us/library/ms191166(v=sql.105).aspx
Upvotes: 1
Reputation: 8120
There are lots of options, one with pure SQL and not requiring any transactional checking as its an atomic statement:
INSERT INTO USER
select ? as username where not exists (select 1 from user where username = ?)
Upvotes: 0