Sam
Sam

Reputation: 2792

check for matching record before insert in JavaDB

Imagine these are my two tables,

Table user_info user_id, user_name, password

I want to compile a Java DB insert statement where the username that is being inserted is checked against the available user_name records and insert if there is no matching user_name!

Well I'm trying to do this,

 insert into user_info (user_name, password) values ('someusername', 'password')
 where not exists (select user_name from user_info where user_name = 'someusername');

Upvotes: 0

Views: 187

Answers (1)

Ernesto Campohermoso
Ernesto Campohermoso

Reputation: 7371

According to documentation: http://download.oracle.com/javadb/10.3.3.0/ref/ref-single.html. You can define a UNIQUE constraint for your column user_name on user_info table. The code is as follows:

ALTER TABLE user_info ADD CONSTRAINT new_unique UNIQUE (user_name);

So when you try to insert an user with an exiting user name JavaDB will throw an exception of violation of constraint.

Upvotes: 1

Related Questions