Parser - CSV files to Oracle database
Hello all,
I wrote a csv parser that parse csv files to micorsoft access database. Now I need to parse the dataset to oracle database. This is part of my exporter class
class MdbExporter : IExporter
/// <summary>
/// Exportiert das DataSet in eine Mdb-Datei.
/// </summary>
/// <param name="ds">Zu exportierendes DataSet.</param>
public void Write(DataSet ds, string[] names)
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + names[0] + ";";
Console.WriteLine("Exporting to database {0} ...", names[0]);
Any ideas how can I do that?
Thanks for any replay in advance.
I wrote a parser that goes through several folders containing csv files, reads them and creates a dataset that contains 15 tables ( which I need for an intranet application after that). I succeed to write a MDB exporter that export this dataset to microsoft access database. Now I need an exporter that will export my dataset to ORACLE database. Below is the full code for my MDB exporter:
public void Write(DataSet ds, string[] names)
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + names[0] + ";";
Console.WriteLine("Exporting to database {0} ...", names[0]);
DbConnection connection = new OleDbConnection(conStr);
try
connection.Open();
catch (DbException e)
ConsoleEx.WriteException(true, e, "Unable to open database: {0}", names[0]);
throw;
DbCommand command = connection.CreateCommand();
foreach (DataTable table in ds.Tables)
Console.WriteLine("\tDeleting table: {0}", table.TableName);
// delete old tables
command.CommandText = string.Format("drop table {0}", table.TableName);
TryExecute(command, false);
// create new
Console.WriteLine("\tCreating new table: {0}", table.TableName);
string[] columnStrings = new string[table.Columns.Count];
for (int i = 0; i < table.Columns.Count; i++)
columnStrings[i] = "`" + table.Columns.ColumnName + "`" + " varchar";
command.CommandText = string.Format("create table {0} ({1})",
table.TableName, string.Join(", \n", columnStrings));
TryExecute(command, true);
// add rows
for (int row = 0; row < table.Rows.Count; row++)
for (int col = 0; col < table.Columns.Count; col++)
columnStrings[col] = "'" + Convert.ToString(table.Rows[row].ItemArray[col]) + "'";
command.CommandText = string.Format("insert into {0} values ({1})",
table.TableName, string.Join(", \n", columnStrings));
TryExecute(command, true);
connection.Close();
I need similar exporter to Oracle database. Starting with SQL LOADER from the beginning its really not a good in my opinion since I am almost done with this approach.
Any help would be appreciated.
Regards,
Sven
Similar Messages
-
How to load excel-csv file into oracle database
Hi
I wanted to load excel file with csv extension(named as trial.csv) into
oracle database table(named as dept),I have given below my experiment here.
I am getting the following error,how should I rectify this?
For ID column I have defined as number(5) datatype, in my control file I have defined as interger external(5),where as in the Error log file why the datatype for ID column is comming as character?
1)my oracle database table is
SQL> desc dept;
Name Null? Type
ID NUMBER(5)
DNAME CHAR(20)
2)my data file is(trial.csv)
ID DNAME
11 production
22 purchase
33 inspection
3)my control file is(trial.ctl)
LOAD DATA
INFILE 'trial.csv'
BADFILE 'trial.bad'
DISCARDFILE 'trial.dsc'
APPEND
INTO TABLE dept
FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(ID POSITION(1:5) INTEGER EXTERNAL(5)
NULLIF ID=BLANKS,
DNAME POSITION(6:25) CHAR
NULLIF DNAME=BLANKS
3)my syntax on cmd prompt is
c:\>sqlldr scott/tiger@xxx control=trial.ctl direct=true;
Load completed - logical record count 21.
4)my log file error message is
Column Name Position Len Term Encl Datatype
ID 1:5 5 , O(") CHARACTER
NULL if ID = BLANKS
DNAME 6:25 20 , O(") CHARACTER
NULL if DNAME = BLANKS
Record 1: Rejected - Error on table DEPT, column ID.
ORA-01722: invalid number
Record 21: Rejected - Error on table DEPT, column ID.
ORA-01722: invalid number
Table DEPT:
0 Rows successfully loaded.
21 Rows not loaded due to data errors.
0 Rows not loaded because all WHEN clauses were failed.
0 Rows not loaded because all fields were null.
Bind array size not used in direct path.
Column array rows : 5000
Stream buffer bytes: 256000
Read buffer bytes: 1048576
Total logical records skipped: 0
Total logical records read: 21
Total logical records rejected: 21
Total logical records discarded: 0
Total stream buffers loaded by SQL*Loader main thread: 0
Total stream buffers loaded by SQL*Loader load thread: 0
5)Result
SQL> select * from dept;
no rows selected
by
balamuralikrishnan.sHi everyone!
The following are the steps to load a excell sheet to oracle table.i tried to be as simple as possible.
thanks
Step # 1
Prapare a data file (excel sheet) that would be uploaded to oracle table.
"Save As" a excel sheet to ".csv" (comma seperated values) format.
Then save as to " .dat " file.
e.g datafile.bat
1,Category Wise Consumption Summary,Expected Receipts Report
2,Category Wise Receipts Summary,Forecast Detail Report
3,Current Stock List Category Wise,Forecast rule listing
4,Daily Production Report,Freight carrier listing
5,Daily Transactions Report,Inventory Value Report
Step # 2
Prapare a control file that define the data file to be loaded ,columns seperation value,name and type of the table columns to which data is to be loaded.The control file extension should be " .ctl " !
e.g i want to load the data into tasks table ,from the datafile.dat file and having controlfile.ctl control file.
SQL> desc tasks;
Name Null? Type
TASK_ID NOT NULL NUMBER(14)
TASK_NAME VARCHAR2(120)
TASK_CODE VARCHAR2(120)
: controlfile.ctl
LOAD DATA
INFILE 'e:\datafile.dat'
INTO TABLE tasks
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
(TASK_ID INTEGER EXTERNAL,
TASK_NAME CHAR,
TASK_CODE CHAR)
The above is the structure for a control file.
Step # 3
the final step is to give the sqlldr command to execute the process.
sqlldr userid=scott/tiger@abc control=e:\controlfile.ctl log=e:\logfile.log
Message was edited by:
user578762 -
How to load the data from .csv file to oracle table???
Hi,
I am using oracle 10g , plsql developer. Can anyone help me in how to load the data from .csv file to oracle table. The table is already created with the required columns. The .csv file is having about 10lakh records. Is it possible to load 10lakh records. can any one please tell me how to proceed.
Thanks in advance981145 wrote:
Can you tell more about sql * loader??? how to know that utility is available for me or not??? I am using oracle 10g database and plsql developer???SQL*Loader is part of the Oracle client. If you have a developer installation you should normally have it on your client.
the command is
sqlldrType it and see if you have it installed.
Have a look also at the FAQ link posted by Marwin.
There are plenty of examples also on the web.
Regards.
Al -
How to mail pdf file from oracle database 11g
Hi,
Using following code to send pdf file from oracle database.
DECLARE
v_From VARCHAR2(80) := '[email protected]';
v_Recipient VARCHAR2(80) := '[email protected]';
v_Subject VARCHAR2(80) := 'test subject';
v_Mail_Host VARCHAR2(30) := '116.214.31.249';
v_Mail_Conn sys.utl_smtp.Connection;
crlf VARCHAR2(2) := chr(13)||chr(10);
BEGIN
v_Mail_Conn := sys.utl_smtp.Open_Connection(v_Mail_Host, 26);
sys.utl_smtp.Helo(v_Mail_Conn, v_Mail_Host);
sys.utl_smtp.Mail(v_Mail_Conn, v_From);
sys.utl_smtp.Rcpt(v_Mail_Conn, v_Recipient);
sys.utl_smtp.Data(v_Mail_Conn,
'Date: ' || to_char(sysdate, 'Dy, DD Mon YYYY hh24:mi:ss') || crlf ||
'From: ' || v_From || crlf ||
'Subject: '|| v_Subject || crlf ||
'To: ' || v_Recipient || crlf ||
'MIME-Version: 1.0'|| crlf || -- Use MIME mail standard
'Content-Type: multipart/mixed;'|| crlf ||
' boundary="-----SECBOUND"'|| crlf ||
crlf ||
'-------SECBOUND'|| crlf ||
'Content-Type: text/plain;'|| crlf ||
'Content-Transfer_Encoding: 7bit'|| crlf ||
crlf ||
'some message text'|| crlf || -- Message body
'more message text'|| crlf ||
crlf ||
'-------SECBOUND'|| crlf ||
'Content-Type: file;'|| crlf ||
' name="D:\mail\pdfSample.pdf"'|| crlf ||
'Content-Transfer_Encoding: 8bit'|| crlf ||
'Content-Disposition: attachment;'|| crlf ||
' filename="D:\mail\pdfSample.pdf"'|| crlf ||
crlf ||
'CSV,file,attachement'|| crlf || -- Content of attachment
crlf ||
'-------SECBOUND--' -- End MIME mail
sys.utl_smtp.Quit(v_mail_conn);
EXCEPTION
WHEN sys.utl_smtp.Transient_Error OR sys.utl_smtp.Permanent_Error then
raise_application_error(-20000, 'Unable to send mail: '||sqlerrm);
END;
Above code executed successfully and mail is send to recipient but file is corrupted.
I think it doesn't pick file from specified location, attachment name is appearing like this 'D:mailpdfsample.pdf
Oracle Database : 11g R2
O.S : windows 7 Professional
Thanks in Advanceparapr wrote:
sys.utl_smtp.Helo(v_Mail_Conn, v_Mail_Host);The above violates RFC 5321 section 4.1.1.1
'-------SECBOUND'|| crlf ||
'Content-Type: file;'|| crlf ||
' name="D:\mail\pdfSample.pdf"'|| crlf ||
'Content-Transfer_Encoding: 8bit'|| crlf ||
'Content-Disposition: attachment;'|| crlf ||
' filename="D:\mail\pdfSample.pdf"'|| crlf ||Invalid Mime header above. Filename are logical. Not physical. Loose the drive and directory names. The filename is there to name the Mime body's content.
crlf ||
'CSV,file,attachement'|| crlf || -- Content of attachmentHow is the above PDF content? This is a string containing the text CSV,file,attachement. Which means when this is what is saved as a PDF file by the mail reader.
EXCEPTION
WHEN sys.utl_smtp.Transient_Error OR sys.utl_smtp.Permanent_Error then
raise_application_error(-20000, 'Unable to send mail: '||sqlerrm);
END;Silly. Why change meaningful exceptions into a generic meaningless exception?? That does not make any sense. -
How to import an .csv file into the database?
and can we code the program in JSP to import the.csv file into the database.
It is better to use Java class to read the CSV file and store the contents in the database.
You can use JSP to upload the CSV file to the server if you want, but don't use it to perform database operations.
JSPs are good for displaying information on the front-end, and for displaying HTML forms, there are other technologies more suitable for the middle layer, back end and the database layer.
So break you application into
1) Front end - JSPs to display input html forms and to display data retrieved from the database.
2) Middle layer - Servlets and JavaBeans to interact with JSPs. The code that reads the CSV file to parse it's contents should be a Java Class in the middle layer. It makes use of Java File I/O
3) Database layer - Connects to the database using JDBC (Java Database Connectivity), and then writes to the database with SQL insert statements.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Keeping the above concepts in mind, first build a simple JSP and get it to work,
then research on Google , for Java File I/O , discover how to read a file,
Then search on how to readh a CSV file using Java.
After researching you should be able to read the CSV file line by line and store each line inside a Collection.
Then research on Google, on how to write to the database using JDBC
Write a simple program that inserts something to a dummy table in the database.
Then, read the data stored in the Collection, and write insert statements for each records in the collection. -
How to import data from excel or csv files to Oracle table
hello everybody,
I am new here and new in Oracle. I would like to know the steps how to import data from excel or csv files to Oracle table.
Let say I already have table inside the Oracle. Then my user give me the sets of data inside the Excel Worksheet.
So, how can I import the excel data into Oracle table.
Thank you in advance.
cheers,
shimaEven easier. Download JDeveloper 11G from this site.
Set up the database connection, right click on the table, select Import->Excel and specify your file to load it. On the import pop-up, you must view and update each tab indicating Columns, Data Types, and DML.
Columns -- move the selected columns that you want to load to the box on the right
Data Types -- select column name from second column to which the data for each column of the import file should load
DML -- click this tab to generate the INSERT SQL
Once done click 'Insert' -
Hello,
I'm currently working on a workflow-project in Oracle APEX with an ORACLE database (10g) where - as a special feature - I have to implement a page where the User can upload a CSV - file into the database tables by himself.
The problem I have is that I don't find a way to fullfill the upload. Is there any special command in ORACLE or predefined scrip to upload a csv - file in an existing table like for example the MYSQL - command LOAD DATA INFILE?Hi,
Just a quick question? are you trying to load data from the cvs or are you loading the file itself into a table. If you're to load data from the cvs then easier Sqlloader else if loading the file itself and Apex then the link will be helpful. or you use this example of web:
CREATE TABLE my_docs
(doc_id NUMBER,
bfile_loc BFILE,
doc_title VARCHAR2(255),
doc_blob BLOB DEFAULT EMPTY_BLOB() );
AS
PROCEDURE doc_dir_setup;
PROCEDURE list (in_doc IN VARCHAR2);
PROCEDURE load (in_doc IN VARCHAR2,
in_id IN NUMBER);
PROCEDURE search (in_search IN VARCHAR2,
in_id IN NUMBER);
END mydocs;
CREATE OR REPLACE PACKAGE BODY
mydocs
AS
vexists BOOLEAN;
vfile_length NUMBER;
vblocksize NUMBER;
PROCEDURE doc_dir_setup IS
BEGIN
EXECUTE IMMEDIATE
'CREATE DIRECTORY DOC_DIR AS'||
'''"E:\jkoopmann\publish\databasejournal\Oracle"''';
END doc_dir_setup;
PROCEDURE list (in_doc IN VARCHAR2) IS
BEGIN
UTL_FILE.FGETATTR('DOC_DIR',
in_doc,
vexists,
vfile_length,
vblocksize);
IF vexists THEN
dbms_output.put_line(in_doc||' '||vfile_length);
END IF;
END list;
PROCEDURE load (in_doc IN VARCHAR2,
in_id IN NUMBER) IS
temp_blob BLOB := empty_blob();
bfile_loc BFILE;
Bytes_to_load INTEGER := 4294967295;
BEGIN
bfile_loc := BFILENAME('DOC_DIR', in_doc);
INSERT INTO my_docs (doc_id, bfile_loc, doc_title)
VALUES (in_id, bfile_loc, in_doc);
SELECT doc_blob INTO temp_blob
FROM my_docs WHERE doc_id = in_id
FOR UPDATE;
DBMS_LOB.OPEN(bfile_loc, DBMS_LOB.LOB_READONLY);
DBMS_LOB.OPEN(temp_blob, DBMS_LOB.LOB_READWRITE);
DBMS_LOB.LOADFROMFILE(temp_blob, bfile_loc, Bytes_to_load);
DBMS_LOB.CLOSE(temp_blob);
DBMS_LOB.CLOSE(bfile_loc);
COMMIT;
END load;
-- in_id can be a db sequence---
PROCEDURE search (in_search VARCHAR2,
in_id NUMBER) IS
lob_doc BLOB;
Pattern VARCHAR2(30);
Position INTEGER := 0;
Offset INTEGER := 1;
Occurrence INTEGER := 1;
BEGIN
Pattern := utl_raw.cast_to_raw(in_search);
SELECT doc_blob INTO lob_doc
FROM my_docs WHERE doc_id = in_id;
DBMS_LOB.OPEN (lob_doc, DBMS_LOB.LOB_READONLY);
Position := DBMS_LOB.INSTR(lob_doc, Pattern, Offset, Occurrence);
IF Position = 0 THEN
DBMS_OUTPUT.PUT_LINE('Pattern not found');
ELSE
DBMS_OUTPUT.PUT_LINE('The pattern occurs at '|| position);
END IF;
DBMS_LOB.CLOSE (lob_doc);
END search;
BEGIN
DBMS_OUTPUT.ENABLE(1000000);
END mydocs;
How to Use
log into your database of choice as the SYS user
compile the package
SQL> @mydocs.sql
set serveroutput on
SQL> set serveroutput on
initial setup of directory object where your documents live
SQL> exec mydocs.doc_dir_setup
Check to make sure you can read one of your documents on disk.
SQL> exec mydocs.list('name.csv');
Load your document into the database
SQL> exec mydocs.load('name.csv', 1);
Search your documents for a string pattern
SQL> exec mydocs.search(Search Pattern', 1);
Regards,
Abby -
Can one import .odarc extention file into oracle database
Hi All,
When we asked client for their production data dump, we got a file with .odarc extention. I googled to find out about this file extention and found info mostly referring to User Productivity Kit. I assume that this file cannot be imported in to oracle database. Since my knowledge about this is limited, I want to find out if it's possible to import this file to oracle database or not. If it's possible what's the work around.
Environment details
OS : Windows server 2003 sp2
Oracle version : 11.2.0.1
Please ask me if the info is insufficient.
Thanks & RegardsOracle can only process files created with :
1. Oracle exp (export tool) with imp
2. Oracle expdp (data pump export) with impdp
3. plain ASCII files with a column based format like CSV with SQL*Loader or external table
4. file containing Oracle SQL statements with SQL*Plus or similar tool.
Any other file type cannot be directly processed by Oracle.
Edited by: P. Forstmann on 17 févr. 2011 09:11 -
Store PDF File in Oracle database 10g
Hi all,
I want to store PDF File in Oracle database 10g,
and then I want to access the pdf file using Oracle Developer 6i
can anyone tell me how to do this,
thanks in advance.This question has already been posted a lot of times.....
See the following:
http://forums.oracle.com/forums/search.jspa?threadID=&q=pdf+file&objID=f82&dateRange=lastyear&userID=&numResults=15
Greetings,
Sim -
How to insert an image file in Oracle database
hi
can you please tell me how to insert an image file into oracle database????
suppose there is one image file in c:\pictures\rose.jpg. how to insert that file into database? theoretically i know that will be BFILE type but i dont know how to insert that.
will be waiting for your reply........
thanks & regards,
PriyatoshHello,
The easiest way to load a blob is to use SQL loader.
This example comes from the utilities guide:
LOAD DATA
INFILE 'sample.dat'
INTO TABLE person_table
FIELDS TERMINATED BY ','
(name CHAR(20),
1 ext_fname FILLER CHAR(40),
2 "RESUME" LOBFILE(ext_fname) TERMINATED BY EOF)
Datafile (sample.dat)
Johny Quest,jqresume.txt,
Speed Racer,'/private/sracer/srresume.txt',
Secondary Datafile (jqresume.txt)
Johny Quest
500 Oracle Parkway
Secondary Datafile (srresume.txt)
Loading LOBs
10-18 Oracle Database Utilities
Speed Racer
400 Oracle Parkway
regards,
Ivo -
How to insert a image file into oracle database
hi all
can anyone guide me how to insert a image file into oracle database now
i have created table using
create table imagestore(image blob);
but when inserting i totally lost don't know what to do how to write query to insert image fileHi I don't have time to explain really, I did have to do this a while ago though so I will post a code snippet. This is using the commons file upload framework.
Firstly you need a multi part form data (if you are using a web page). If you are not using a web page ignore this bit.
out.println("<form name=\"imgFrm\" method=\"post\" enctype=\"multipart/form-data\" action=\"FileUploadServlet?thisPageAction=reloaded\" onSubmit=\"return submitForm();\"><input type=\"FILE\" name=\"imgSource\" size='60' class='smalltext' onKeyPress='return stopUserInput();' onKeyUp='stopUserInput();' onKeyDown='stopUserInput();' onMouseDown='noMouseDown(event);'>");
out.println(" <input type='submit' name='submit' value='Submit' class='smalltext'>");
out.println("</form>"); Import this once you have the jar file:
import org.apache.commons.fileupload.*;Now a method I wrote to upload the file. I am not saying that this is correct, or its the best way to do this. I am just saying it works for me.
private boolean uploadFile(HttpServletRequest request, HttpSession session) throws Exception {
boolean result = true;
String fileName = null;
byte fileData[] = null;
String fileUploadError = null;
String imageType = "";
String error = "";
DiskFileUpload fb = new DiskFileUpload();
List fileItems = fb.parseRequest(request);
Iterator it = fileItems.iterator();
while(it.hasNext()){
FileItem fileItem = (FileItem)it.next();
if (!fileItem.isFormField()) {
fileName = fileItem.getName();
fileData = fileItem.get();
// Get the imageType from the filename extension
if (fileName != null) {
int dotPos = fileName.indexOf('.');
if (dotPos >= 0 && dotPos != fileName.length()-1) {
imageType = fileName.substring(dotPos+1).toLowerCase();
if (imageType.equals("jpg")) {
imageType = "jpeg";
String filePath = request.getParameter("FILE_PATH");
session.setAttribute("filePath", filePath);
session.setAttribute("fileData", fileData);
session.setAttribute("fileName", fileName);
session.setAttribute("imageType", imageType);
return result;
} And now finally the method to actually write the file to the database:
private int writeImageFile(byte[] fileData, String fileName, String imageType, String mode, Integer signatureIDIn, HttpServletRequest request) throws Exception {
//If the previous code found a file that can be uploaded then
//save it into the database via a pstmt
String sql = "";
UtilDBquery udbq = getUser(request).connectToDatabase();
Connection con = null;
int signatureID = 0;
PreparedStatement pstmt = null;
try {
udbq.setUsePreparedStatements(true);
con = udbq.getPooledConnection();
con.setAutoCommit(false);
if((!mode.equals("U")) || (mode.equals("U") && signatureIDIn == 0)) {
sql = "SELECT SEQ_SIGNATURE_ID.nextval FROM DUAL";
pstmt = con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
signatureID = rs.getInt(1);
if (fileName != null && imageType != null) {
sql = "INSERT INTO T_SIGNATURE (SIGNATURE_ID, SIGNATURE) values (?,?)";
InputStream is2 = new ByteArrayInputStream(fileData);
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, signatureID);
pstmt.setBinaryStream(2, is2, (int)(fileData.length));
pstmt.executeUpdate();
pstmt.close();
con.commit();
con = null;
if(mode.equals("U") && signatureIDIn != 0) {
signatureID = signatureIDIn.intValue();
if (fileName != null && imageType != null) {
sql = "UPDATE T_SIGNATURE SET SIGNATURE = ? WHERE SIGNATURE_ID = ?";
InputStream is2 = new ByteArrayInputStream(fileData);
pstmt = con.prepareStatement(sql);
pstmt.setBinaryStream(1, is2, (int)(fileData.length));
pstmt.setInt(2, signatureID);
pstmt.executeUpdate();
pstmt.close();
con.commit();
con = null;
} catch (Exception e) {
con = null;
throw new Exception(e.toString());
return signatureID;
} -
Loading data from .csv file into Oracle Table
Hi,
I have a requirement where I need to populate data from .csv file into oracle table.
Is there any mechanism so that i can follow the same?
Any help will be fruitful.
Thanks and regardsYou can use Sql Loader or External tables for your requirement
Missed Karthick's post ...alredy there :)
Edited by: Rajneesh Kumar on Dec 4, 2008 10:54 AM -
How to export the data from an excel file to Oracle database by using macro
Hi,
I want to export data from an excel file into Oracle database.There is one method that by creating the macros through excel we are able to do this.
can anybody please send me the code to create macros?
Thanks in advance.
Regards,
Surendra.VThere are several resources on the web, but you could start analyzing if this code fits your needs --> VBA Macro for Excel 2003 Export of Text File with Comma and Quote Delimiters.
~ Madrid -
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. -
Flat file to Oracle Database - Invalid Month
Hi All
I am New to XI and trying to create a simple interface between Legacy system (flat file) and Oracle database.
I have some date fields in the Oracle table.
When i run the interface it says "invalid month" with some SQL exception number.
I am using (mm/dd/yyyy) format for the date.
Is there any conversion i need to do. I am using XML SQL format for Oracle database.
Any help is appreciated.
Thanks
NagakishoreHello,
Oracle is very picky with the way date is stored. Assume that you have a field datefield that you need to save. In mapping add an attribute hasqQuote and set it to "NO". When mapping the value to the node use to_date as shown below.
<DateField hasQuot="No">
TO_DATE("2004-07-20", "yyyy-mm-dd hh:mi:ss")</DateField>
cheers,
Naveen
Maybe you are looking for
-
How do I transfer an iphoto library to a USB HD?
My Macbook Pro is being fixed at the Apple Store about an hour away from where I live. I need to erase, reinstall, and ship the machine while I am in Des Moines. I have my essential documents backed up already but didn't get a chance to back up the i
-
My device is not showing up on the latest iTunes Update (12.1)
I have an iPod Touch 4th Gen. I plug in my iPod with the USB cord, and it can charge, but it does not show up as a device on iTunes. I have tried turning off my iPod, restarting my computer, and re-installing iTunes. If someone could help, that would
-
Select statement takes very long
Hello from Germany, how comes that from one week to another my select-statement "select MAX(PRIMARYKEY) from mytable t where t.IntegerColumn = 5" takes 20times longer (25s) than before (0,4s)? The RowCount of myTable is 89899. Best Regards Marlon
-
I am the account holder of BT phone. I have used BT for more than 1 year. My package is Unlimited Evening and Weekend Plan. I'll be back my country this May. Do I need to pay for cancelling my contract? If yes, How much does it cost? Many thanks, An.
-
Android open pdf at particular page
Hi I am developing an Android app in which I want to open PDF at a specific page. Is it possible by mentioning the same in Intent parameters or specific Adobe Pramaters. Thanks !