Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / Databases / August 2005

Tip: Looking for answers? Try searching our database.

Java Prepared Statement with multiple arguments

Thread view: 
johnfofawn@hotmail.com - 03 Aug 2005 15:47 GMT
Hi,

I need to insert data into a table only if that data does not already
exist.

So I want to do something like

IF NOT EXIST (SELECT * FROM MyTable WHERE MyColumn = '?') INSERT INTO
MyTable (MyColumn) VALUES ('?')

In this example there is only one column, but in my real table I have
about 10 columns.

So I can create a prepared statement to do this, but since I use two
?'s for each column (one for the select and another for the insert) I
have to set each column value twice.

Am I using this right? Is there a better way to do this?

THANKS!
John
joeNOSPAM@BEA.com - 03 Aug 2005 17:42 GMT
Hi. Yes you have to have a '?' for every variable in both clauses. If
you make a stored procedure like:

create procedure myInsertProc int @foo, VARCHAR(30) @bar ...
AS
BEGIN
  IF NOT EXIST (SELECT * FROM MyTable WHERE MyColumn = @foo
  AND MYOtherColumn = @bar ) INSERT INTO
MyTable (MyColumn) VALUES (@foo, @bar)
END

then your JDBC would only need one '?' for each column:

p = c.prepareStatement("{ call myInsertProc( ?, ? ) }");

If you can create an index for your table that enforces that
each row is unique, then you don't need to do the check. If
the row already exists the insert will fail.

HTH,
Joe Weinstein at BEA
johnfofawn@hotmail.com - 03 Aug 2005 18:29 GMT
Joe,

That's perfect. Thank you!!!!

John
Jim Harrington - 05 Aug 2005 18:48 GMT
If you want to avoid the stored procedure, you could do the following
as well:

INSERT INTO MyTable (MyColumn)
SELECT '?' FROM DUAL
WHERE NOT EXISTS (SELECT * FROM MyTable
                 WHERE MyColumn = '?');

> Joe,
>
> That's perfect. Thank you!!!!
>
> John


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.