File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes JDBC and the fly likes sql Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Databases » JDBC
Bookmark "sql" Watch "sql" New topic
Author

sql

raj baig
Ranch Hand

Joined: Jul 11, 2006
Posts: 96
Hi,
In my database i have user table contains user_id,password,email.
To insert a new row i am checking for the email.if email already exists
i am generating error message the email already exist.
Here my problem is i am interacting db twice.
1.select query returns true if user exists
2.insert data if select query returns false.

But i want this should happen in a single query.
Can you tell me how to do it.


Thanks in Advance,
Raj.
Purushoth Thambu
Ranch Hand

Joined: May 24, 2003
Posts: 425
One simple thing you can do is declare email as primary key. You don't have to fire the query to check if email already exists or not.
raj baig
Ranch Hand

Joined: Jul 11, 2006
Posts: 96
Hi,
Userid column is already a primary key column.
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

Originally posted by Purushothaman Thambu:
One simple thing you can do is declare email as primary key. You don't have to fire the query to check if email already exists or not.


This is only a good idea is you know for certain that a user's email address will never change. Far safer is a surrogate key.


But i want this should happen in a single query.

Can't be done in a single query. Well, you could wrap the two steps up in a Stored Procedure, but then all you are doing is hiding that it has two steps. You could define a unique index on email and report the constraint violation to the user. However, this is using Exceptions as conditionals which is not usually considered a good thing to do. Your two query idea is probably the best way to handle this. If your email address has to be unique, I'd declare the constraint too.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
mnadeem chishti
Greenhorn

Joined: Aug 07, 2006
Posts: 11
check the column names "password" is reserver word for oracle so rename this colum.
Chris Hendy
Ranch Hand

Joined: Mar 04, 2006
Posts: 98
In ORACLE you can do the following

INSERT INTO your_table (pk_col, col1, col2, ...)
SELECT pk_val, val1, val2, ...
FROM dual
WHERE NOT EXISTS (SELECT 1 FROM your_table WHERE pk_col = pk_val1);

Where DUAL is a supplied table guaranteed to have one row. For other RDBMS you can create your own version.

If you wrap this in a stored procedure and return SQL%ROWCOUNT then this will be 1 if the insert succeded and 0 if it failed. And you are only hitting the database once in the stored procedure, and only making one network roundtrip.
[ April 12, 2007: Message edited by: Chris Hendy ]
raj baig
Ranch Hand

Joined: Jul 11, 2006
Posts: 96
Thanks All
 
GeeCON Prague 2014
 
subject: sql