How to read a remote file into a db
I need to open and read a file, and then insert records according into several tables. How can i do that, when the file is not on the same maschine as the db itself.
Thanks!
Daniel
Use sql*loader. You can load a file on your PC or a network directory.
Similar Messages
-
How to read/write .CSV file into CLOB column in a table of Oracle 10g
I have a requirement which is nothing but a table has two column
create table emp_data (empid number, report clob)
Here REPORT column is CLOB data type which used to load the data from the .csv file.
The requirement here is
1) How to load data from .CSV file into CLOB column along with empid using DBMS_lob utility
2) How to read report columns which should return all the columns present in the .CSV file (dynamically because every csv file may have different number of columns) along with the primariy key empid).
eg: empid report_field1 report_field2
1 x y
Any help would be appreciated.If I understand you right, you want each row in your table to contain an emp_id and the complete text of a multi-record .csv file.
It's not clear how you relate emp_id to the appropriate file to be read. Is the emp_id stored in the csv file?
To read the file, you can use functions from [UTL_FILE|http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/u_file.htm#BABGGEDF] (as long as the file is in a directory accessible to the Oracle server):
declare
lt_report_clob CLOB;
l_max_line_length integer := 1024; -- set as high as the longest line in your file
l_infile UTL_FILE.file_type;
l_buffer varchar2(1024);
l_emp_id report_table.emp_id%type := 123; -- not clear where emp_id comes from
l_filename varchar2(200) := 'my_file_name.csv'; -- get this from somewhere
begin
-- open the file; we assume an Oracle directory has already been created
l_infile := utl_file.fopen('CSV_DIRECTORY', l_filename, 'r', l_max_line_length);
-- initialise the empty clob
dbms_lob.createtemporary(lt_report_clob, TRUE, DBMS_LOB.session);
loop
begin
utl_file.get_line(l_infile, l_buffer);
dbms_lob.append(lt_report_clob, l_buffer);
exception
when no_data_found then
exit;
end;
end loop;
insert into report_table (emp_id, report)
values (l_emp_id, lt_report_clob);
-- free the temporary lob
dbms_lob.freetemporary(lt_report_clob);
-- close the file
UTL_FILE.fclose(l_infile);
end;This simple line-by-line approach is easy to understand, and gives you an opportunity (if you want) to take each line in the file and transform it (for example, you could transform it into a nested table, or into XML). However it can be rather slow if there are many records in the csv file - the lob_append operation is not particularly efficient. I was able to improve the efficiency by caching the lines in a VARCHAR2 up to a maximum cache size, and only then appending to the LOB - see [three posts on my blog|http://preferisco.blogspot.com/search/label/lob].
There is at least one other possibility:
- you could use [DBMS_LOB.loadclobfromfile|http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_lob.htm#i998978]. I've not tried this before myself, but I think the procedure is described [here in the 9i docs|http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96591/adl12bfl.htm#879711]. This is likely to be faster than UTL_FILE (because it is all happening in the underlying DBMS_LOB package, possibly in a native way).
That's all for now. I haven't yet answered your question on how to report data back out of the CLOB. I would like to know how you associate employees with files; what happens if there is > 1 file per employee, etc.
HTH
Regards Nigel
Edited by: nthomas on Mar 2, 2009 11:22 AM - don't forget to fclose the file... -
How to read\write text file into oracle database.
Hello,
I am having text file called getInfo in c:\temp folder. I would like to populate data from text file to data base. How to proceed. Could anybody help me out.
Thanks,
ShailuHere is a web page with easy to follow instructions regarding external files: http://www.adp-gmbh.ch/ora/misc/ext_table.html.
Now I understand what all the excitement is over external tables.
"External tables can read flat files (that follow some rules) as though they were ordinary (although read-only) Oracle tables. Therefore, it is convenient to use external tables to load flat files into the DB." -from the above link. -
How to read a flat file into a report?
The file format is like below:
Company Code : BUKRS(header)
Posting Period :3(header)
Then The items data is started as a table format.
Line items in table format.
If anybody knows the answer please share with me.Use the GUI_UPLOAD Program to upload the file from Presentation server to SAP.
Sample code:
*& Report Z_UPLOAD_MUNCPCODE *
REPORT z_upload_muncpcode.
PARAMETERS : p_fname LIKE rlgrap-filename.
TYPES: BEGIN OF ty_munc,
land1 TYPE tzone-land1,
zone1 TYPE tzone-zone1,
vtext TYPE tzont-vtext,
END OF ty_munc.
DATA: i_munc TYPE STANDARD TABLE OF ty_munc,
i_tzone TYPE STANDARD TABLE OF tzone,
i_tzont TYPE STANDARD TABLE OF tzont,
wa_munc TYPE ty_munc,
wa_tzone TYPE tzone,
wa_tzont TYPE tzont.
CONSTANTS: c_path TYPE char20 VALUE 'C:\',
c_mask TYPE char9 VALUE ',*.*,*.*.',
c_mode TYPE char1 VALUE 'O',
c_filetype TYPE char10 VALUE 'ASC',
c_x TYPE char01 VALUE 'X'.
AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_fname.
*-- Browse Presentation Server
PERFORM f4_presentation_file.
START-OF-SELECTION..
*-- Read presentation server file
PERFORM f1003_pre_file.
LOOP AT i_munc INTO wa_munc.
wa_tzone-mandt = wa_tzont-mandt = sy-mandt.
wa_tzone-land1 = wa_tzont-land1 = wa_munc-land1.
wa_tzone-zone1 = wa_tzont-zone1 = wa_munc-zone1.
wa_tzont-spras = sy-langu.
wa_tzont-vtext = wa_munc-vtext.
APPEND wa_tzont TO i_tzont.
APPEND wa_tzone TO i_tzone.
CLEAR: wa_munc, wa_tzont, wa_tzone.
ENDLOOP.
END-OF-SELECTION.
Modify Table TZONT
PERFORM enqueue_table USING text-001.
MODIFY tzont FROM TABLE i_tzont.
PERFORM dequeue_table USING text-001.
Modify Table TZONE
PERFORM enqueue_table USING text-002.
MODIFY tzone FROM TABLE i_tzone.
PERFORM dequeue_table USING text-002.
WRITE: 'Tables TZONE & TZONT are updated'.
*& Form f4_presentation_file
*& F4 Help for presentation server
FORM f4_presentation_file .
CALL FUNCTION 'WS_FILENAME_GET'
EXPORTING
def_path = c_path
mask = c_mask
mode = c_mode
title = text-001
IMPORTING
filename = p_fname
EXCEPTIONS
inv_winsys = 1
no_batch = 2
selection_cancel = 3
selection_error = 4
OTHERS = 5.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
ENDFORM. " f4_presentation_file
*& Form f1003_pre_file
*& Upload File
FORM f1003_pre_file .
DATA: lcl_filename TYPE string.
lcl_filename = p_fname.
CALL FUNCTION 'GUI_UPLOAD'
EXPORTING
filename = lcl_filename
filetype = c_filetype
has_field_separator = c_x
TABLES
data_tab = i_munc
EXCEPTIONS
file_open_error = 1
file_read_error = 2
no_batch = 3
gui_refuse_filetransfer = 4
invalid_type = 5
no_authority = 6
unknown_error = 7
bad_data_format = 8
header_not_allowed = 9
separator_not_allowed = 10
header_too_long = 11
unknown_dp_error = 12
access_denied = 13
dp_out_of_memory = 14
disk_full = 15
dp_timeout = 16
OTHERS = 17.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
EXIT.
ENDIF.
ENDFORM. " f1003_pre_file
*& Form enqueue_table
*& Enqueue Table
FORM enqueue_table USING p_tabname.
CALL FUNCTION 'ENQUEUE_E_TABLE'
EXPORTING
tabname = p_tabname
EXCEPTIONS
foreign_lock = 1
system_failure = 2
OTHERS = 3.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
ENDFORM. " enqueue_table
*& Form dequeue_table
*& Dequeue Table
FORM dequeue_table USING p_tabname.
CALL FUNCTION 'DEQUEUE_E_TABLE'
EXPORTING
tabname = p_tabname.
ENDFORM. " dequeue_table
Prakash. -
How to read an excel file into the datatable in sdk code( AddonApplication)
Hi Experts,
Please let me know the code ,how to write an excel file to the datatable and based on the datatable it should write to the database table.
help would be appreciated...
Regards,
Vijay Kumar
Edited by: Haroon Rasheed on Oct 29, 2011 10:40 PMHi,
You may check: Read Excel File by Sheet then put it in Matrix
Thanks,
Gordon -
How to read a gif file into the java file?
i want to read an image(*.gif) file into my appication. can u plz help me in this?
Hi
I have made a program that display images here is the code i hope it helps
package ImageProcessing;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageProcessing
public static Image imRead(String imagePath)
Image im = null;
try
File imageFile = new File(imagePath);
im = ImageIO.read(imageFile);
catch(Exception e)
e.printStackTrace();
return im;
public void imWrite(Image im,String fileFormat,String imagePath) throws IOException
File outputFile = new File(imagePath);
ImageIO.write((RenderedImage) im, fileFormat, outputFile);
public static void imShow(String imagePath)
ImageObserver io = null;
JFrame frame = new JFrame();
Image im = imRead(imagePath);
ShowImage imShow = new ShowImage(im);
frame.add(imShow);
frame.setVisible(true);
frame.setTitle(imagePath);
frame.setSize(im.getWidth(io),im.getHeight(io));
frame.setResizable(false);
frame.show();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public static void main(String[] args) throws IOException
imShow("D:\\My Computer\\Images\\Cash2.gif");
package ImageProcessing;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
public class ShowImage extends Panel
Image im;
public ShowImage(Image inputIm)
im = inputIm;
public void paint(Graphics g)
g.drawImage(im, 0, 0, null);
} -
How to read the CSV Files into Database Table
Hi
Friends i have a Table called tblstudent this has the following fields Student ID, StudentName ,Class,Father_Name, Mother_Name.
Now i have a CSV File with 1500 records with all These Fields. Now in my Program there is a need for me to read all these Records into this Table tblstudent.
Note: I have got already 2000 records in the Table tblstudent now i would like to read all these CSV File records into the Table tblstudent.
Please give me some examples to do this
Thank your for your service
Cheers
Jofin1) Read the CSV file line by line using BufferedReader.
2) Convert each line (record) to a List and add it to a parent List. If you know the columns before, you might use a List of DTO's.
3) Finally save the two-dimensional List or the List of DTO's into the datatable using plain JDBC or any kind of ORM (Hibernate and so on).
This article contains some useful code snippets to parse a CSV: http://balusc.xs4all.nl/srv/dev-jep-csv.html -
How to read and writre file into remote machine in the network
HI Experts,
i want to write the data and read data into file in remote machine(not in application server and presentation server).is it possible in abap.
thanks in advance
With Regads
NaiduHi naidu,
1. We can use this type of path
computername
folder
file.ext
2. We can use this in GUI_UPLOAD
and it will run on presentation server,
connect to
computer
and read the file contents.
regards,
amit m. -
Help! How to read a .txt file into a Java class and make 2D array?
Hi guys,
Im a newbie with arrays, just started really using them.. please bear with me if I don't seem to understand much..
I have a .txt file that contains either a square or rectangle (random width and length).. How can I read each line into a Java class into a 2D array with rows and columns?Example :
import javax.swing.*;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class ReadInto2DArrayExample {
public static void main(String[] args) {
ArrayList array = new ArrayList();
char [][] twoDimesionArray = null;
try
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
File file = fileChooser.getSelectedFile();
BufferedReader reader = new BufferedReader(new FileReader(file));
String data;
//Read from file
while ((data = reader.readLine()) != null)
//Convert data to char array and add into array
array.add(data.toCharArray());
reader.close();
//Creating a 2D char array base on the array size
twoDimesionArray = new char [array.size()][];
//Convert array from ArrayList to 2D array
for (int i = 0; i < array.size(); i++)
twoDimesionArray[i] = (char [])array.get(i);
//Test the 2D Array
for (int y = 0; y < twoDimesionArray.length; y++)
char [] temp = twoDimesionArray[y];
for (int x = 0; x < temp.length; x ++ )
System.out.print(temp[x]);
System.out.println("");
catch (Exception ex)
ex.printStackTrace();
} -
How to read a CSV file into the portal
hi all,
I want to read the content of CSV file that is avaliable in my desktop.
plz help me with suitable code
Regards
Savitha
Edited by: Savitha S R on Jun 1, 2009 8:25 AMPlease use this code for that
REPORT znkp_upload_csv line-size 400.
DATA : v_filename TYPE string.
PARAMETER : p_file LIKE rlgrap-filename DEFAULT 'C:\Documents and Settings\Administrator\Desktop\JV.csv' .
*Types for Reading CSV file
TYPES : BEGIN OF x_csv,
text(400) TYPE c,
END OF x_csv.
*Global internal table for reading CSV file
DATA : lt_csv TYPE TABLE OF x_csv.
*Global work area for reading CSV file
DATA : wa_csv LIKE LINE OF lt_csv.
v_filename = p_file.
CALL FUNCTION 'GUI_UPLOAD'
EXPORTING
filename = v_filename
FILETYPE = 'ASC'
HAS_FIELD_SEPARATOR = ' '
HEADER_LENGTH = 0
READ_BY_LINE = 'X'
DAT_MODE = ' '
CODEPAGE = ' '
IGNORE_CERR = ABAP_TRUE
REPLACEMENT = '#'
CHECK_BOM = ' '
VIRUS_SCAN_PROFILE =
NO_AUTH_CHECK = ' '
IMPORTING
FILELENGTH =
HEADER =
TABLES
data_tab = lt_csv
EXCEPTIONS
file_open_error = 1
file_read_error = 2
no_batch = 3
gui_refuse_filetransfer = 4
invalid_type = 5
no_authority = 6
unknown_error = 7
bad_data_format = 8
header_not_allowed = 9
separator_not_allowed = 10
header_too_long = 11
unknown_dp_error = 12
access_denied = 13
dp_out_of_memory = 14
disk_full = 15
dp_timeout = 16
OTHERS = 17
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
DATA : BEGIN OF item OCCURS 0 ,
t1(20) TYPE c,
t2(20) TYPE c,
t3(20) TYPE c,
t4(20) TYPE c,
t5(20) TYPE c,
t6(20) TYPE c,
t7(20) TYPE c,
t8(20) TYPE c,
END OF item.
DATA : txt(1) TYPE c. " 1-Header 2-Item
LOOP AT lt_csv into wa_csv.
split wa_csv-text at ',' into item-t1
item-t2
item-t3
item-t4
item-t5
item-t6
item-t7
item-t8.
append item.
clear item.
ENDLOOP.
Check ITEM TABLE
Regards
Naresh -
How to read a text file into a String?
and also write a text file from a String. I searched the forum and found this folowing code:
// Read and append... by Example
try{
String fileName = "text.txt"; // Filename
// Make the inputfile object
FileInputStream fi = new FileInputStream(fileName);
byte inData[] = new byte[fi.available()];
fi.read(inData); // Read
fi.close(); // Close
String text = new String(inData); // Make a textstring...
// Now, do whatever you want with the data... and append...
String textToAppend = "kjkjhjhKJ";
byte outData[] = textToAppend.getBytes();
// Make the outputfile (whith the 'append' boolean set to true
FileOutputStream fo = new FileOutputStream(fileName,true);
fo.write(outData);
fo.close();
}catch(Exception oops){}but it returns funny characters to the String from the text file and vice versa in writting the text file. Can anybody please help? Thank you.
kindoSee here for info on encodings:
http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html
Some common US encodings and common uses:
ASCII (DOS)
Cp1252 (Windows 9x)
UTF8 (XML)
import java.io.*;
public class TextFile extends File
private static String DEFAULT_ENCODING = "ASCII";
private File file;
private String encoding;
public TextFile(File file, String encoding)
super(file.getPath());
this.file = file;
this.encoding = encoding;
public TextFile(File file)
this(file, DEFAULT_ENCODING);
public String load() throws Exception
FileInputStream fis = new FileInputStream(file);
byte[] barr = new byte[fis.available()];
fis.read(barr);
fis.close();
return new String(barr, encoding);
public void save(String str) throws Exception
FileOutputStream fos = new FileOutputStream(file);
fos.write(str.getBytes(encoding));
fos.close();
} -
How to read an XML file into a java program?
hi,
i want to load the following very simple xml file in my java program.
<root>
<weblogic>
<url value="t3://192.168.1.160:7001" />
<context value="weblogic.jndi.WLInitialContextFactory" />
</weblogic>
</root>
I am getting the error: " Line=1: cvc-elt.1: Cannot find the declaration of element 'root'."
What might be the problem can anyone help me out.
My java class code is:
public class BIXMLReader {
/** All output will use this encoding */
static final String outputEncoding = "UTF-8";
// Parses an XML file and returns a DOM document.
// If validating is true, the contents is validated against the DTD
// specified in the file.
public static Document parseXmlFile(String filename, boolean validating) {
try {
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setIgnoringComments(false);
factory.setIgnoringElementContentWhitespace(false);
factory.setCoalescing(false);
factory.setValidating(validating);
// Create the builder and parse the file
System.out.println("filename = " + filename);
DocumentBuilder db = factory.newDocumentBuilder();
// Set an ErrorHandler before parsing
OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, outputEncoding);
db.setErrorHandler(new MyErrorHandler(new PrintWriter(errorWriter, true)));
Document doc = db.parse(new File(filename));
System.out.println(doc.toString());
return doc;
} catch (SAXException e) {
System.out.println("A parsing error occurred; the xml input is not valid. " + e.getMessage());
} catch (ParserConfigurationException e) {
System.out.println("Parser configuration exception has occured");
} catch (IOException e) {
System.out.println("IO Exception has occured " + e.getMessage());
return null;
// Error handler to report errors and warnings
private static class MyErrorHandler implements ErrorHandler {
/** Error handler output goes here */
private PrintWriter out;
MyErrorHandler(PrintWriter out) {
this.out = out;
* Returns a string describing parse exception details
private String getParseExceptionInfo(SAXParseException spe) {
String systemId = spe.getSystemId();
if (systemId == null) {
systemId = "null";
String info = "URI=" + systemId +
" Line=" + spe.getLineNumber() +
": " + spe.getMessage();
return info;
// The following methods are standard SAX ErrorHandler methods.
// See SAX documentation for more info.
public void warning(SAXParseException spe) throws SAXException {
out.println("Warning: " + getParseExceptionInfo(spe));
public void error(SAXParseException spe) throws SAXException {
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
public void fatalError(SAXParseException spe) throws SAXException {
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}ok thanks, i can get the elements, but why did it not validate it?
I want to read the child nodes of "weblogic" not by their name but by their index. Because i dont want to confine the reader so i want to read all the child nodes of weblogic (looping over them). i m doing the following but its not returning me the correct result and giving me the wrong count of child nodes.
Element elementNode = (Element)doc.getElementsByTagName("weblogic").item(0);
NodeList nodeList = elementNode.getChildNodes();
int length = nodeList.getLength();
System.out.println("length = "+ length); // the length its giving is 5 but i shuld get only 2
for(int i=0; i < length; i++) {
Element elmChild = (Element) nodeList.item(i);
System.out.println(elmChild.getAttribute("value"));
what might be the problem? -
How can i read local excel file into internal table in webdynpro for abap a
Could someone tell me how How can i read local excel file into an internal table in webdynpro for abap application.
thank u for your replyDeep,
File manuplations...............................
1. At the presentation level:
->GUI_UPLOAD
->GUI_DOWNLOAD
->CL_GUI_FRONTEND
2. At the application server level:
->OPEN DATASET : open a file in the application server for reading or writing.
->READ DATASET : used to read from a file on the application server that has been opened for reading
-> TRANSFER DATASET : writing data to a file.
-> CLOSE DATASET : closes the file
-> DELETE DATASET : delete file
If file is on the local PC,use the function module GUI_UPLOAD to upload it into an internal table by passing the given parameters......
call function 'GUI_UPLOAD'
exporting
filename = p_file
filetype = 'ASC'
has_field_separator = '#'
tables
data_tab = t_data
p_file : excel file path.
t_data : internal table
<b>reward points if useful.</b>
regards,
Vinod Samuel. -
I shot video on a Panasonic P2 and I'm trying to import the MXF files to Final Cut Pro but when I try to import, the only thing that imports is a blurry image of each clip. There's no audio and no video...how can I import MXF files into Final Cut Pro?
at the end, you say "import preferences", which program are you describing?
So im safer using footage that is remotely being pulled from iphoto...
vs
using footage that is imported into FCP from imovie?
Is there anything i can do in fcp to make this footage more reliable or safer or more stable as i pull remotely from iphoto?
All the footage, and all the libraries to all programs, or on a new pegasus 12tb raid 5 setup fyi. -
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;
}
Maybe you are looking for
-
Fast refreshable Mview question.
Hi All, Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production PL/SQL Release 11.1.0.7.0 - Production "CORE 11.1.0.7.0 Production" TNS for Linux: Version 11.1.0.7.0 - Production NLSRTL Version 11.1.0.7.0 - Production Can
-
Snow Leopard + Flash 10.3.181.14 Plugin + Freeze
• Mac OS X 10.6.7 • MacPro 12GB RAM • Latest Safari Build • Flash Plugin (System Preferences Pane) 10.3.181.14 • Adobe Flash CS4 10.0.2 • Coda 1.7 While all Flash objects in all of my browsers (Safari, Chrome, FF, etc) work perfectly, when using Coda
-
I have been told that my i-tunes is probably corrupted. How do I uninstall the corrupted i-tunes and install an i-tunes that is not corrupted? Will this automatically be sync.ed to my i-phone4s and i-pad once corrected on my emachine computer?
-
Hi All, I am very new to ADF and given a task to learn how to work in ADF. Can anyone please help me and tell how to start learnig ADF from the beginners stage. with regards, Dwitikrushna Pattanaik.
-
How well does the Blackberry desktop software work on a Mac
I have friend who syncs his BB 8830 a lot on his current PC. He his considering a switch to a Mac and wanted to know how well the BB desktop software works on a Mac. How would you answer that question? Will the BB desktop software sync calendars and