How to pass a array of object to oracle procedure using callable
Hi,
I am calling a oracle stored procedure using callable statement which has IN and OUT parameter of same type.
IN and OUT are array of objects. (ie) IN parameter as Array of Objects and OUT parameter as Array of Objects
here are the steps i have done as advised from oracle forum. correct me if i am in wrong direction
ORACLE types and Stored Procedure
CREATE OR REPLACE
TYPE APPS.DEPARTMENT_TYPE AS OBJECT (
DNO NUMBER (10),
NAME VARCHAR2 (50),
LOCATION VARCHAR2 (50)
CREATE OR REPLACE
TYPE APPS.DEPT_ARRAY AS TABLE OF department_type;
CREATE OR REPLACE package body APPS.insert_object
IS
PROCEDURE insert_object_prc (d IN dept_array, d2 OUT dept_array)
IS
BEGIN
d2 := dept_array ();
FOR j IN 1 .. d.COUNT
LOOP
d2.EXTEND;
d2 (j) := department_type (d (j).dno, d (j).name, d(j).location);
END LOOP;
END insert_object_prc;
END insert_object;
JAVA CODE
Value Object
package com.custom.vo;
public class Dep {
public int empNo;
public String depName;
public String location;
public int getEmpNo() {
return empNo;
public void setEmpNo(int empNo) {
this.empNo = empNo;
public String getDepName() {
return depName;
public void setDepName(String depName) {
this.depName = depName;
public String getLocation() {
return location;
public void setLocation(String location) {
this.location = location;
to call stored procedure
package com.custom.callable;
import com.custom.vo.Dep;
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleTypes;
import oracle.jdbc.pool.OracleDataSource;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.Datum;
import oracle.sql.STRUCT;
import oracle.sql.StructDescriptor;
public class CallableArrayTryOut {
private static OracleDataSource odcDataSource = null;
public static void main(String[] args) {
OracleCallableStatement callStatement = null;
OracleConnection connection = null;
try {
odcDataSource = new OracleDataSource();
odcDataSource
.setURL("......");
odcDataSource.setUser("....");
odcDataSource.setPassword("....");
connection = (OracleConnection) odcDataSource.getConnection();
} catch (Exception e) {
System.out.println("DB connection Exception");
e.printStackTrace();
Dep[] dep = new Dep[2];
dep[0] = new Dep();
dep[0].setEmpNo(100);
dep[0].setDepName("aaa");
dep[0].setLocation("xxx");
dep[1] = new Dep();
dep[1].setEmpNo(200);
dep[1].setDepName("bbb");
dep[1].setLocation("yyy");
try {
StructDescriptor structDescriptor = new StructDescriptor(
"APPS.DEPARTMENT_TYPE", connection);
STRUCT priceStruct = new STRUCT(structDescriptor, connection, dep);
STRUCT[] priceArray = { priceStruct };
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(
"APPS.DEPT_ARRAY", connection);
ARRAY array = new ARRAY(arrayDescriptor, connection, priceArray);
callStatement = (OracleCallableStatement) connection
.prepareCall("{call insert_object.insert_object_prc(?,?)}");
((OracleCallableStatement) callStatement).setArray(1, array);
callStatement.registerOutParameter(2, OracleTypes.ARRAY,
"APPS.DEPT_ARRAY");
callStatement.execute();
ARRAY outArray = callStatement.getARRAY(2);
Datum[] datum = outArray.getOracleArray();
for (int i = 0; i < datum.length; i++) {
oracle.sql.STRUCT os = (oracle.sql.STRUCT) datum[0];
Object[] a = os.getAttributes();
for (int j = 0; j < a.length; j++) {
System.out.print("Java Data Type :"
+ a[j].getClass().getName() + "Value :" + a[j]
+ "\n");
connection.commit();
callStatement.close();
} catch (Exception e) {
System.out.println("Mapping Error");
e.printStackTrace();
THE ERROR
Mapping Errorjava.sql.SQLException: Inconsistent java and sql object types
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
at oracle.jdbc.dbaccess.DBError.check_error(DBError.java:1130)
at oracle.sql.StructDescriptor.toOracleArray(StructDescriptor.java:823)
at oracle.sql.StructDescriptor.toArray(StructDescriptor.java:1735)
at oracle.sql.STRUCT.<init>(STRUCT.java:136)
at com.custom.callable.CallableArrayTryOut.main(CallableArrayTryOut.java:48)
You posted this question in the wrong forum section. There is one dedicated to Java that was more appropriate.
Anyway here is a link that describes what you should do.
http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/oraarr.htm#i1049179
Bye Alessandro
Similar Messages
-
I m also trying for How to pass Object to a procedureb using OCCI...
Steps....
1. I created A type.....
2. Then I created a VARRAY using that Type.
3.After that I have written An Procedure with object as a parameter..
now using OCCI how do u bind the parameter with this . plz note that using OTT
i have already created the class representation of above object type i.e class
four Files Created 1> demo.h 2>registermapping.h
3> demo.cpp 2>registermapping.cpp
After I want to Pass the Values in A Vector...
vctor<full_name *> vect;
stmt=con->createStatement("BEGIN Add_Object(:1); END;");
full_name *name1 = new full_name; //Giving the Error here Given below....
name1->
name1->
Through name1 Which Function I will call in which I will Pass a String....
like
name1->readSQL("Sanjay"); Or I have to add a function......
vect.push_back(name1);
setVector(stmt,1,vect,"FULL_NAME");
error C2259: 'FullName' : cannot instantiate abstract class
can u plz suggest me Why this Error is Giving......?
How to pass the data?
setFirst_name() and setLast_name() this two function I will add in Demo.cpp which one created automativcally by Using OTT command.....or other way plz tell me Boss ....
Can u lz Suggest me ASAP....hi Nishant ,
What u have done Now I mm trying ....
can u Plz Suggest me......
How to pass and Array of Object in Procedure using OCCI... Doing....
90% finished Two Error's Are Coming...
1> If I create the Class then Data Not Inserting table......
2> If I will create the Class through OTT command.......
then U can't Instantiate Object It is DIsplying ,this is Abstract Class(PObject)...
Beco'z the below Method is Not adding Automatically by OTT command which is Pure Virtual Function.....
But I added this Function Still SAme Error Giving..
getSQLTypeName(oracle::occi::Environment env, void *schName,
unsigned int &schNameLen, void **typeName,
unsigned int &typeNameLen) const
Plz Suggest me....
regard's
sanjay -
Passing an array of objects to stored procedure(oracle)
I have to pass an array of objects to a pl/sql stored proc.
Its prototype is,
proc_orderins(ordernum varchar2(14), ct newTask)
where newTask is an array of objects:
type task as object ( name varchar2(20),odd varchar2(8),sdd varchar2(8));
create or replace type newTask as VARRAY(25) OF Task;
will the following work from the java code :
public class CriticalTask
String name,odd,sdd;
public CrticalTask(String name,String odd,String sdd)
this.name=name;
this.odd=odd;
this.sdd=sdd;
Object [] ctasks =new Object[7];
for(i=0;i<7;i++)
Object=new CrtitcalTask("x","x","x");
String query="{call proc_orderins(?,?)}";
CallableStatement cstmt=con.prepareCall(query);
cstmt.setInt(123);
cstmt.setObject(ctasks);
cstmt.execute();
will the above code work, when I am passing an array?Use code tags when you post code.
I am rather certain that the code you posted will not work.
Technically you should be able to use the java.sql.Array interface.
The newest Oracle drivers might support that (you would have to investigate how to use it.)
It is however possible that it isn't supported. If not then you will have to use one of the Oracle specific classes that is documented in the Oracle jdbc documentation. -
How to pass the arguments dynamically to a Oracle procedure.
Hi all..
How to pass the arguments dynamically to a procedure.
Thanks in Advance.I have a concurremt program which has 5 parameters right now. The user can add more parameters from front end as per their requirement.
So that time.. the 6th parameter has to add to my procedure dynamically.
Thanks. -
Passing an array of objects.
I have been trying to pass an array of objects from java to C. They are simple objects, only fields, no methods.
Example...
class User
String name;
int id;
public class JNIExample
User[] users = new User[10];
public native void nativeCode(User[] usersarray);
static
try{
System.loadLibrary("object");
}catch(Exception e)
System.out.println("Could not load library.");
public static void main(String[] args)
JNIExample anex = new JNIExample();
anex.nativeCode(anex.users);
Could someone give me sample code on how to access the array elements and get/set the object values on the C side. In the above code I did not create any of the objects in the array or set their field values but these will be set on the java side.
Any help would be greatly appr.
Thanks,
DarrinJNIEXPORT void JNICALL Java_User_nativeCode
(JNIEnv *env, jobject this, jobjectArray arr) {
jsize idx; // array index
// accessing the Users
for(idx = env->GetArrayLength(env, arr); idx-- > 0;) {
jobject user = env->GetObjectArrayElement(env, arr, idx);
// do something with it
// setting the Users
for(idx = env->GetArrayLength(env, arr); idx-- > 0;) {
jobject user = ...
env->SetObjectArrayElement(env, arr, idx, user);
} -
How to list an array of objects using struts in jsp and ActionForm
I am using the struts ActionForm and need to know how to display an Array of objects. I am assuming it would look like this in the ActionForm:
private AddRmvParts addRmv[];
But I am not sure how the getter and setter in the ActionForm should look. Should it be a Collection or an Iterator?
I am thinking I need to use an iterator in the jsp page to display it.
I am also wondering if the AddRmvParts class I have can be the same class that gets populated by the retrieval of data from the database. This class has 10 fields that need to display on the jsp page in 1 row and then multiple rows of these 10 fields.
Thanks.Most probably the easiest way to make it accessible in your page is as a collection.
ie
public Collection getAddRmvParts()
You can use the <logic:iterate> or a <c:forEach>(JSTL) tag to loop through the collection
As long as the individual items in the collection provide get/set methods you can access them with the dot syntax:
Example using JSTL:
<c:forEach var="addRmvPart" items="${addRmvParts}">
<c:out value="${addRmvPart.id} ${addRmvPart.name} ${addRmvPart.description}"/>
</c:forEach> -
Passing an array of objects to a method.
Hi I'm building a program to act as a CD Collection Database. An array of objects represents the entries: Artist, Album and NUmber of Tracks. What I want to do is in the Menu, user to choose wether he or she wants to Add new CD to collection, print or quit, if he/she does then I call a method addNewEntry, to which i pass the array of objects called array, and I want the user to enter the entries each in turn, after that i want the program to return to the method Menu and ask if he or she wants to quit, print or add new cd. The idea is that the details entered already would be contained in the array of objects [0], so the next set of details go to [1] and then to [2] and so on. I have build up the code at this stage but i get an error while copmiling and im totally stuck. Im a beginner in Java.
Here is the code:
//by Andrei Souchinski
//Mini Project: CD Collection Database
//Designed for a grade F
//Defining new class of objects to represent CD database entries.
//A database entry consists of the artist name, the album name and number of tracks.
//A single entry can be entered by the user typing the details in and the entry can be printed out.
import javax.swing.*;
import java.util.*;
public class MiniProject
public static void main (String[] args)
System.out.println("\tCD Collection Database\n");
System.out.println("1. Add new Compact Disk to the Database");
System.out.println("2. Print out current database entries");
System.out.println("3. Quit\n");
theMenu();
public static void theMenu()
CompactDisk [] array = new CompactDisk[20];
String menu;
menu = JOptionPane.showInputDialog("What would you like to do?");
if (menu.equals ("3"))
JOptionPane.showMessageDialog(null, "Thank You For Using our Service! \nGoodbye!");
System.exit(0);
if (menu.equals ("2"))
if (menu.equals ("1"))
addNewEntry(array);
else
JOptionPane.showMessageDialog(null, "Please select your choice form the menu");
theMenu();
public int addNewEntry(int newcd[])
int i;
newcd[i] = (JOptionPane.showInputDialog("Please enter the name of the Artist"));
newcd[i] = (JOptionPane.showInputDialog("Please enter the name of the Album"));
newcd[i] = (Integer.parseInt (JOptionPane.showInputDialog("Please enter the number of tracks on this album")));
//A Compact Disk entry consists of three attributes: artist name, album and number of tracks
class CompactDisk
public String artistname; //Instance variables for artistname, albumname and numberoftracks.
public String albumname;
public int numberoftracks;
public CompactDisk(String n, String a, int t)
artistname = n; //Stores the 1st argument passed after "new Dates" into day
albumname = a; //Stores the 2nd argument passed after "new Dates" into month
numberoftracks = t; //Stores the 3rd argument passed after "new Dates" into year
//When called from the main method, prints the contents of
//artistname, albumname and numberoftracks on to the screen.
public void printCompactDisk ()
String output = "\n " + artistname + "\n " + albumname + "\n " + numberoftracks;
System.out.println(output);
}//by Andrei Souchinski
//Mini Project: CD Collection Database
//Designed for a grade F
//Defining new class of objects to represent CD database entries.
//A database entry consists of the artist name, the album name and number of tracks.
//A single entry can be entered by the user typing the details in and the entry can be printed out.
import javax.swing.*;
import java.util.*;
public class MiniProject
public static void main (String[] args)
System.out.println("\tCD Collection Database\n");
System.out.println("1. Add new Compact Disk to the Database");
System.out.println("2. Print out current database entries");
System.out.println("3. Quit\n");
theMenu();
public static void theMenu()
String menu;
menu = JOptionPane.showInputDialog("What would you like to do?");
if (menu.equals ("3"))
JOptionPane.showMessageDialog(null, "Thank You For Using our Service! \nGoodbye!");
System.exit(0);
if (menu.equals ("2"))
if (menu.equals ("1"))
addNewEntry();
else
JOptionPane.showMessageDialog(null, "Please select your choice form the menu");
theMenu();
public static void addNewEntry()
CompactDisk [] array = new CompactDisk[20];
int i = 0;
array.artistname = (JOptionPane.showInputDialog("Please enter the name of the Artist"));
array[i].albumname = (JOptionPane.showInputDialog("Please enter the name of the Album"));
array[i].numberoftracks = (Integer.parseInt (JOptionPane.showInputDialog("Please enter the number of tracks on this album")));
//A Compact Disk entry consists of three attributes: artist name, album and number of tracks
class CompactDisk
public String artistname; //Instance variables for artistname, albumname and numberoftracks.
public String albumname;
public int numberoftracks;
public CompactDisk(String n, String a, int t)
artistname = n; //Stores the 1st argument passed after "new Dates" into day
albumname = a; //Stores the 2nd argument passed after "new Dates" into month
numberoftracks = t; //Stores the 3rd argument passed after "new Dates" into year
//When called from the main method, prints the contents of
//artistname, albumname and numberoftracks on to the screen.
public void printCompactDisk ()
String output = "\n " + artistname + "\n " + albumname + "\n " + numberoftracks;
System.out.println(output);
I've edited the code, itcompiles, but gives an error when i ran it..:( -
How to pass int array as an IN parameter to PLSQL Procedure
Hi,
How to pass int array in java to a stored procedure througn jdbc
and what type of data type I should declare to this IN parameter
in PLSQL Procedure.
Thanks,
SimiHi,
The best way to do what you want depends on what you want. Start by describing what you need to do. It's best to post some sample data (CREATE TABLE and INSERT statments) and what results you want from that sample data. (See the forum FAQ: https://forums.oracle.com/message/9362002)
If you have ideas about how to do the job (e.g., populating a temporary table) it can be helpful to include those, too, but distinguish clearly between WHAT you need to do and HOW you might do it.
As Bencol suggested, a SYS_REFCURSOR might be the best way to pass back the results.
Since you didn't post your table, or even describe what you wanted to do with it, I'll illustrate using scott.emp, which is probably on your system.
Say you wanted a procedure that took a DATE as an argument, and returned a some designated columns (empno, ename and hiredate in the example below) for all employees hired on or after the given DATE. You might write a procedure like this:
CREATE OR REPLACE PROCEDURE hired_since
( start_date IN DATE
, out_data OUT SYS_REFCURSOR
AS
BEGIN
OPEN out_data FOR
SELECT empno, ename, hiredate
FROM scott.emp
WHERE hiredate >= start_date;
END hired_since;
SHOW ERRORS
You can test it in SQL*Plus like this:
VARIABLE c REFCURSOR
EXEC hired_since (DATE '1982-01-01', :c);
PRINT :c
The output I got from this test was:
EMPNO ENAME HIREDATE
7788 SCOTT 19-APR-87
7876 ADAMS 23-MAY-87
7934 MILLER 23-JAN-82 -
How to pass xml data as objects into Database using store procedures
Hi All,
I don't have much knowledge on store procedure,can anybody help how to pass the xml as objects in Database using store procedure.
My Requirement is I have a table with three fields EMPLOYEE is table name and the fields are EMP_ID,EMP_TYPE AND EMP_DET,I have to insert the employees xml data into corresponding fields in the table.
Input Data
<ROWSET>
<ROW>
<EMP_ID>7000</EMP_ID>
<EMP_TYPE>TYPE1</EMP_TYPE>
<EMP_DET>DEP</EMP_DET>
<ROW>
<ROW>
<EMP_ID>7000</EMP_ID>
<EMP_TYPE>TYPE2</EMP_TYPE>
<EMP_DET>DEP2</EMP_DET>
<ROW>
<ROW>
<EMP_ID>7000</EMP_ID>
<EMP_TYPE>TYPE3</EMP_TYPE>
<EMP_DET>DEP3</EMP_DET>
<ROW>
<ROWSET>
So each row values has to inserted into resp fields in the table.
Regards
ManiDo you have a similar structure in your stored procedure ?
In that case you can simply call the procedure from soa using db adapter and do a mapping to assign the values. -
I am ussing a DLL created by another party. I have the list of the C declaretions. I have been able to write a seq that can turn the comport ON/OFF or select a different port but I have not been able to send or recieved any data. I have created an array of bytes(unsigned 8-bit integers)to send and recieved data but nothing goes out or in.
Hi Toro,
There is an example in your \Examples\AccessingArrays\PassingArrayParametersToDLL directory that illustrates exactly how to pass TestStand arrays as arguments to dll functions. The source files for the .dll are located in the same directory.
For more information on passing arrays as parameters to modules you should read the "DLL Flexible Prototype Adapter" section of Chatper 13 in the TestStand User Manual, and pay special attention to the subsection entitled "Array Parameters". You can access the User Manual from the TestStand Start Menu group, the TestStand Sequence Editor's Help menu, the \Doc directory, or online at the following link:
http://digital.ni.com/manuals.nsf/websearch/50B69DA356B8D38C86256A0000660E6B?OpenDocumen
t&node=132100_US
Jason F.
Applications Engineer
National Instruments
www.ni.com/ask -
How to pass an array to a stored procedure
create or replace package demo_pkg
as
type cityArray is table of city%rowtype index by binary_integer;
procedure city_report( p_inputs in cityArray );
end;
CREATE OR REPLACE PACKAGE BODY demo_pkg
AS
PROCEDURE city_report (p_inputs IN cityarray)
IS
BEGIN
FOR i IN 1 .. p_inputs.COUNT
LOOP
DBMS_OUTPUT.put_line ( 'citycode = '
|| p_inputs (i).city_code
|| ' CITYDESCRIPTION = '
|| p_inputs (i).city_description
INSERT INTO testing
(city_code, city_description
VALUES (p_inputs (i).city_code, p_inputs (i).city_description
commit;
END LOOP;
END;
END;
to call that procedure ia m using this
declare
my_data demo_pkg.cityArray;
begin
my_data(1).city_code := 1234;
my_data(1).CITY_DESCRIPTION := 10;
my_data(2).city_code := 4567;
my_data(2).CITY_DESCRIPTION := 20;
my_data(3).city_code := 4321;
my_data(3).CITY_DESCRIPTION := 30;
demo_pkg.city_report( my_data );
end;
but actually the procedure (demo_pkg.city_report)is called from front end(.net).how they will call this procedure in .net invironmentHi,
Your exact question has been asked before, see: http://asktom.oracle.com/pls/ask/search?p_string=How+to+pass+an+array+to+a+stored+procedure
or do a search on this forum.
And please use this tag => (yes, just the 4 characters forming the word 'code' between curly brackets)
*before* and *after* your example to maintain formatting and indentation, it's hard to read now.... -
How to pass an Array to jsp:param
Hi,
I am trying to find out how to pass an array to a jsp:param tag abnd then retrieve
the values in the next page. Please help soon. Thanks
Here's my code - Assume the books array has more than 1 value
String[] books = request.getParameterValues("book");
<jsp:include page="<%=contentPage%>" flush="true">
<jsp:param name="bookSelected" value="<%= books %>" />
</jsp:include>
The 'contentPage' takes me to the next page where I have the following to retrieve
the value of 'bookSelected'
String[] bookSelected = request.getParameter("bookSelected");
I tried accessing the array like this
if(bookSelected.equals("book1"))
but did not succeed.
I tried accessing the array in a loop but it did not work. Here's what I tried.
<jsp:include page="<%=contentPage%>" flush="true">
<%for (int i = 0; i<books.length; i++){
%>
<jsp:param name="bookSelected" value="<%= books %>" />
<% } %>
</jsp:include>
Hi
tell me how you redirect from __confirmdelete.jsp:__ to deleteServlet.java..
and post detail code of __confirmdelete.jsp:__ -
How to bind arrays to PL/SQL stored procedure using OCI?
Hi,
We are having problems trying to bind arrays to PL/SQL stored procedure using OCI. Here is the situation:
- We have a stored procedure called "GetVEPFindTasks" with the following interface:
PROCEDURE GetVEPFindTasks (
p_ErrorCode OUT NUMBER,
p_ErrorMsg OUT VARCHAR2,
p_RowCount OUT NUMBER,
p_VEPFindTasks OUT t_VEPFindTaskRecordTable,
p_MaxTask IN NUMBER);
t_VEPFindTaskRecordTable is a record with the following entries:
TYPE t_VEPFindTaskRecord IS RECORD (
RTCID NUMBER,
TransNum NUMBER,
TransTimestamp VARCHAR2(20),
Pathname1 image_data.pathname%TYPE,
Pathname2 image_data.pathname%TYPE,
Pathname3 image_data.pathname%TYPE,
OperatorID operator.id%TYPE);
- Now, we are trying to call the stored procedure from C++ using OCI (in UNIX). The call that we use are: OCIBindByName and OCIBindArrayOfStruct to bind the parameters to the corresponding buffers. We bind all parameters in the interface by name. Now, we do bind the record's individual item by name (RTCID, TransNum, etc.), and not as a record. I don't know if this is going to work. Then, we use the bind handles of the binded record items (only record items such as RTCID, TransNum, and NOT error_code which is not part of the record) to bind the arrays (using OCIBindArrayOfStruct).
All of the parameters that are binded as arrays are OUTPUT parameters. The rest are either INPUT or INPUT/OUTPUT parameters. Now, when we try to execute, OCI returns with an error "Invalid number or types of arguments" (or something to that sort... the number was something like ORA-06550). Please help...
Is there any sample on how to use the OCIBindArrayOfStruct with PL/SQL stored procedures? The sample provided from Oracle is only for a straight SQL statement.
Thank's for all your help.
** Dannil Chan **As you said:
You have to pass in an array for every field and deconstruct/construct the record in the procedure. There is no support for record type or an array of records. Can you give me a example? I'am very urgently need it.
thanks
email: [email protected] -
How to pass Unix environment variable to a SQL procedure or SQL * Plus
Can any body suggest me how to ,
How to pass Unix environment variable to a SQL procedure or SQL * Plus file..
I am trying to invoke a SQL Procedure from Unix
by passing the value of a Unix environment variable.
Is it possible..?
Thanks in advance.
Regards,
Srinivas JaltaruWithin your shell script you can use what is known as a "here document" which is basically a way of wrapping a call to Oracle. The following call to Oracle loops and writes rows to files with numerically increasing file names. Two unix shell variables are used, one in a select statement and one in a spool command :
<pre>
#!/bin/bash
export ORACLE_SID=DEV05
FILENO=1007351
while [ ${FILENO} -le 1008400 ]
do
FILENAME=farm_${FILENO}.txt
DUMMY=`sqlplus -s user20/user20 <<SQLSTOP
set lines 73
set pages 0
set head off
set termout off
set echo off
set feedback off
select rpad(searchx, 8)
from blastx@PRODUCTION
where searchx = ${FILENO} ### here's a shell variable
spool /export/home/user20/sql/psiblast/BACKUP2_D/${FILENAME} ### here's a shell variable
spool off
SQLSTOP`
FILENO=`expr ${FILENO} + 1`
done
exit 0
</pre> -
How To Store pdf or doc file in Oracle Database using Java Jdbc?
can any one help me out How To Store pdf or doc file in Oracle Database using Java Jdbc in JSP/Serlet? i tried like anything. using blob also i tried. but i am able 2 store images in DB not files. please if u know or else if u have some code like this plz send that to me, and help me out plz. i need that urgent.
Hi.. i am not getting error, But i am not getting the original contents from my file. i am getting all ASCII vales, instead of my original data. here i am including my code.
for Adding PDF in DB i used image.jsp
Database table structure (table name. pictures )
Name Null? Type
ID NOT NULL NUMBER(11)
IMAGE BLOB
<%@ page language="java" import="java.util.*,java.sql.*,java.io.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.135:1521:orcl","scott","tiger");
PreparedStatement ps,pstmt,psmnt;
ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)");
File file =
new File("D:/info.pdf");
FileInputStream fs = new FileInputStream(file);
ps.setInt(1,4);
ps.setBinaryStream(2,fs,fs.available());
int i = ps.executeUpdate();
if(i!=0){
out.println("<h2>PDF inserted successfully");
else{
out.println("<h2>Problem in image insertion");
catch(Exception e){
out.println("<h2>Failed Due To "+e);
%>
O/P: PDF inserted successfully
i tried to display that pdf using servlet. i am giving the code below.
import java.io.IOException;
import java.sql.*;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DispPDF extends HttpServlet {
* The doGet method of the servlet. <br>
* This method is called when a form has its tag value method equals to get.
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html"); i commented. coz we cant use response two times.
//PrintWriter out = response.getWriter();
try{
InputStream sPdf;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.135:1521:orcl","scott","tiger");
PreparedStatement ps,pstmt,psmnt;
psmnt = con.prepareStatement("SELECT image FROM pictures WHERE id = ?");
psmnt.setString(1, "4"); // here integer number '4' is image id from the table.
ResultSet rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
//out.println(bytearray);
int size=0;
sPdf = rs.getBinaryStream(1);
response.reset();
response.setContentType("application/pdf");
while((size=sPdf.read(bytearray))!= -1 ){
//out.println(size);
response.getOutputStream().write(bytearray,0,size);
catch(Exception e){
System.out.println("Failed Due To "+e);
//out.println("<h2>Failed Due To "+e);
//out.close();
OP
PDF-1.4 %âãÏÓ 2 0 obj <>stream x+är á26S°00SIá2PÐ5´1ôÝ BÒ¸4Ü2KüsSSS4C²ê Pkø$VãGÒU×713CkW )(Ü endstream endobj 4 0 obj <>>>/MediaBox[0 0 595 842]>> endobj 1 0 obj <> endobj 3 0 obj <> endobj 5 0 obj <> endobj 6 0 obj <> endobj xref 0 7 0000000000 65535 f 0000000325 00000 n 0000000015 00000 n 0000000413 00000 n 0000000168 00000 n 0000000464 00000 n 0000000509 00000 n trailer <<01b2fa8b70ac262bfa939cc786f8770c>]/Root 5 0 R/Size 7/Info 6 0 R>> startxref 641 %%EOF
plz help me out.
Maybe you are looking for
-
Spry Horizontal Menu Bar background image IE8 not visible.
I have a slight problem with a horizontal menu bar that I have placed on my site and am hoping someone can help me. It views fine in Firefox, however in IE8 the top menu background image is white instead of the image I specified. Firefox image is bel
-
Help with flexible panels in Accordian
I can't seem to get my panels to work as flexible when viewed in a browser. The scroll bars are gone, but only the first line of text shows up. Here's what I tried... I changed CSS of AccordianPanelContent to this... .AccordionPanelContent { ove
-
Does Edge Animate CC have an auto-save function?
Hi there, I'm migrating from Flash to Edge Animate. In Flash there is a customisable auto-save option - each 10 minutes, each 30 minutes etc. Is Adobe Edge Animate has something similar to this?
-
HT6208 how do I transfer I Phone contacts to AOL contacts on my PC?
How do I transfer IPhone Contacts to my PC Aol Address book?
-
Amortization of Goodwill after method change
Hi all, Need some help. It is not really clear to me how does BCS take into account (equity-method)goodwill, and further more - amortization of goodwill, in/after Method Change activity. Business scenario Step 1. Company "A" (equity - 1000 monetary u