I created 2 types as OBJECT and a type of table and a nested table in my Oracle database. I know how to inset a row in table in cmd but I have no idea that how I can insert a row in this table with PreparedStatement
in Java.
This is my table and type:
CREATE Or REPLACE TYPE item AS OBJECT
(
id number,
counter number
);/
CREATE Or REPLACE TYPE time AS OBJECT
(
year number,
month number,
second number
);
CREATE Or REPLACE TYPE Shoping_list AS TABLE OF item;
create table invoice(
id number NOT NULL PRIMARY KEY ,
list shoping_list,
dateIn date,
timeIn time,
totalCost number )
nested table list store as list_of_product;
I can insert with this code in cmd
insert into invoice(id,list,dateIn,timeIn,totalCost) values(seq_ID_invoice.nextval,
shoping_list(item(1,2),item(26,1)),TO_DATE('1396-04-11','YYYY-MM-DD'),time(11,25,40),7000);
and this my java code
preparedStatement = connection.prepareStatement("insert into invoice (id,list,dateIn,timeIn,totalCost) values ("+id+",?,?,?,?)");
seq_ID_invoice
is Oracle Sequence. So oracle takes its value automatically. For rest you can use setInt, setString, setFloat, etc. methods
available in PreparedStatement
based on the types of columns defined inside your table.
Following sample code may help you.
PreparedStatement ps = connection.prepareStatement(
"insert into invoice(id, list, dateIn, timeIn, totalCost)"+
" values (seq_ID_invoice.nextval, shoping_list(item(?,?), item(?,?)), TO_DATE(?,'YYYY-MM-DD'), time(?, ?, ?), ?)");
ps.setInt(1, int_value_for_id_of_item_1);
ps.setInt(2, int_value_for_counter_of_item_1);
ps.setInt(3, int_value_for_id_of_item_2);
ps.setInt(4, int_value_for_counter_of_item_2);
ps.setString(5, string_value_for_date);
ps.setInt(6, int_value_for_year_of_time);
ps.setInt(7, int_value_for_month_of_time);
ps.setInt(8, int_value_for_second_of_time);
ps.setInt(9, int_bvalue_for_total_cost);
int rowCnt = ps.executeUpdate();
System.out.println(rowCnt+" rows affected.");
int_value_for_id_of_item_1, int_value_for_counter_of_item_1, ...
these are java variables. You can defined variables of your choice or you can directly mention values in place of these variables.