Sunday, 29 September 2013

NETBEANS PL/SQL - INSERT RECORD ONLY IF RECORD DOES NOT EXIST

NETBEANS PL/SQL - INSERT RECORD ONLY IF RECORD DOES NOT EXIST

I got no good answers to my question, found out how to do it. This is how
you would insert a record to a table only if the record does not already
exist:
Create or Replace function on your schema (this is checking 2 parameters,
you can set it to check as many as you wish) PL/SQL is very specific ,
copying and pasting as I have written should compile successfully. It took
many tries to get the syntax just right. This function checks the Table to
be written to, and the corresponding column names to be checked if they
already exist together.
create or replace function Found(var1 type, var2 type)return number is
numberOfSelectedRows number := 0;
begin select count(*) into numberOfSelectedRows from TABLE where
COLUMN_NAME = var1 and COLUMN_NAME = var2;
return numberOfSelectedRows;
end Found;
========================================================================================
2. Write the java to execute the pl/sql function: this is done with
NetBeans. When the button is clicked, it takes FORM data- loaded from
other tables, and determines whether or not the record already exists in
the table to be inserted into.
try {
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(""+LOGIN.url+"");
String str1 = jTextField_VariableName.getText();
String str2 = jTextField_VariableName.getText();
String q = "insert into TABLE (var1 type, var2 type) VALUES
('"+str1+"', '"+str2+"')" ;
cs = con.prepareCall("{?=call Found(?, ?)}"); // cs =
CallableStatement - defined in class CallableStatement cs = null;
cs.setString(2, str1);
cs.setString(3, str2);
cs.registerOutParameter(1, Types.INTEGER);
cs.execute();
if(cs.getInt(1)>= 1)
{
JOptionPane.showMessageDialog(null, " this record already
exists");
}
else
{
try{
DriverManager.registerDriver (new
oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(""+LOGIN.url+"");
pst = con.prepareStatement(q);
pst.execute();
}catch(SQLException ex)
{Logger.getLogger(REGISTER_STUDENT.class.getName()).log(Level.SEVERE,
null, ex);}
}
} catch (SQLException ex)
{Logger.getLogger(REGISTER_STUDENT.class.getName()).log(Level.SEVERE,
null, ex);}

No comments:

Post a Comment