Store a byte[] in a SQLServer DB

I try to stock a byte[] in a image field of SQLServer DB
I'm doing so :
EAIForm myForm = (EAIForm)form;
FormFile ff = myForm.getFile();
byte[] file=ff.getFileData();
String EAIQuery ="INSERT INTO ecopeople_prd.dbo.EAI (personalID,docName,datas,dateDoc,comm) VALUES ('"+myForm.getPersonalID()+"','"+name+"','"+file+"','"+myForm.getDate()+"','"+myForm.getComm()+"')";
but het pass for file [9@34ER56 in place of the byte array ..

Hi,
in your case I would use a PreparedStatement where you can set the different parameters with the correct type. So the code would look something like this PreparedStatement stmt = connection.getPreparedStatement("INSERT INTO ecopeople_prd.dbo.EAI " +
        "(personalID,docName,datas,dateDoc,comm) VALUES (?,?,?,?,?)");
stmt.setInt(1, myForm.getPersonalID());         // assuming it's an integer
stmt.setString(2, name);
stmt.setBytes(3, file);
stmt.setDate(4, myForm.getDate());
stmt.setObject(5, myForm.getComm());          // don't know the typeThen you have no problem inserting your file data and the correct representation of the different values because JDBC is already doing that for you.
Hope it helps.

Similar Messages

  • How to store multiple bytes

    Ok, the problem I am currently having that gives me a 6f00 (unknown) error is due to the way I am reading in data and storing it in my loop. My code is as follows:
    byte[] buffer = apdu.getBuffer();
    byte numBytes = buffer[ISO7816.OFFSET_LC];     
    byte byteRead = (byte)(apdu.setIncomingAndReceive());
    if (numBytes != byteRead){
    ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
    byte ind = ISO7816.OFFSET_CDATA;
    for (short index=0x0000; index <numBytes; index=+0x0001)
    first[(short)index] = buffer[(short)(ind)];
         ind = ind ++;
    What I am trying to do is to store the bytes of data from the script file into my first array. I have tried many different variations on this. I know that this is where I'm getting errors because it works if I only use one byte. If anyone knows what could be causing my problem, I'd appreciate your help. Thank you.

    Use the Util.arrayCopy(....) instead of looping like that

  • Store Multi Byte Characters in WE8ISO8859P1 Database without Migration

    Hi - I am looking for a solution where I can store the Multi Byte Character's under the WE8ISO8859P1 Database.
    Below are the DB NLS_PARAMETERS
    NLS_CHARACTERSET = WE8ISO8859P1
    NLS_NCHAR_CHARACTERSET = AL32UTF8
    NLS_LENGTH_SEMANTICS = BYTE
    Size of DB = 2 TB.
    DB Version = 11.2.0.4
    Currently there is a need to store the Chinese Characters under NAME and ADDRESS Columns only. Below are the description of the columns.
    Column Name            DataType
    GIVEN_NAME_ONE
    VARCHAR2(120 BYTE)
    GIVEN_NAME_TWO
    VARCHAR2(120 BYTE)
    LAST_NAME
    VARCHAR2(120 BYTE)
    ADDR_LINE_ONE
    VARCHAR2(100 BYTE)
    ADDR_LINE_TWO
    VARCHAR2(100 BYTE)
    ADDR_LINE_THREE
    VARCHAR2(100 BYTE)
    What are my option's over here without considering the Migration WE8ISO8859P1  DB to AL32UTF8 ?
    1. Can I increase the size of the Column i.e make it n x 4. e.g NAME will be 480 Byte  and ADDRESS will be 400 Byte.? What are pros and cons ?
    2. Convert the existing Column from VARCHAR2 to NVARCHAR2 with the Same Size ? i.e NVARCHAR2(120 BYTE) ?
    3. Add the extension to an table with new columns - NVARCHAR2. e.g NAME - NVARCHAR2(120 CHAR) and ADDRESS (100 - CHAR) ?
    4. Database got Clobs,Blobs, Long etc. got Varied Data, Is it a good idea to Migrate to AL32UTF8  with Minimal Downtime ?
    Please suggest the best alternatives. Thanks.
    Thanks
    Jitesh

    Hi Jitesh,
    NLS_NCHAR_CHARACTERSET can either be AL16UTF16 or UTF8. So mostly your DB would have UTF8.
    You can definitely insert Unicode characters into N-type columns. Size of the N-type column will depend on the characters you plan to store in them.
    If you use N-types, do make sure you use the (N'...') syntax when coding it so that Literals are denoted as being in the national character set by prepending letter 'N'.
    Although you can use them, N-types are  not very well supported in 3the party client/programming environments, you may need to adapt a lot of code to use N-types properly and there are some limitations.
    While at first using N-types for a (few) columns seems like a good idea to avoid the conversion of a whole database , in many cases the end conclusion is that changing the NLS_CHARACTERSET is simply the easiest and fastest way to support more languages in an Oracle database.
    So, It depends on how much of your data will be unicode which you would store in N-type characters.
    If you do have access to My Oracle Support you can check Note 276914.1 :The National Character Set ( NLS_NCHAR_CHARACTERSET ) in Oracle 9i, 10g , 11g and 12c, For more details.
    With respect to your Downtime, The actual conversion (CSALTER or in case using DMU) shouldn't take too much time, if you have run CSSCAN on your DB and made sure you have taken care of all your truncation, convertible and lossy data (if any).
    It would be best for you to run CSSCAN initially to gauge how much convertible/lossy/truncation data you need to take care.
    $ CSSCAN FROMCHAR=WE8ISO8859P1 TOCHAR=AL32UTF8 LOG=P1TOAl32UTF8 ARRAY=1000000 PROCESS=2 CAPTURE=Y FULL=Y
    Regards,
    Suntrupth

  • Follow up to How to store multiple bytes

    So, instead of using that for loop, the whole loop will be replaced by something like
    first [ ] = Util.Arraycopy(byteRead); ???
    or should it be Util.Arraycopy(buffer);

    assuming the array is nonatomic,
    Util.arrayCopyNonAtomic( apduBuffer, ISO7816.OFFSET_CDATA,first, (short)0,bytesRead)
    if you are maintaining an atomic array, the arguments are same, method is different Util.arrayCopy(...)

  • How to store webpage content into sqlserver

    HI All,
    I would like to thank all guys who are helping here.
    I need some help I will be very happy if guys can help me I am sure you will helping as the question which I am about to ask is nothing to the seniors here. My query goes here...
    I have a page called www dot abc dot com and there is some content in that page now I want to store this content in an
    sqlserver.
    I heard that it can be achieved using DOM can you guys help in this. If not in DOM please suggest me the possible ways.
    Bunch of thanks in advance.Please help me ASAP as it is very urgent to my project.
    Sowmya

    997387 wrote:
    HI All,
    I would like to thank all guys who are helping here.
    I need some help I will be very happy if guys can help me I am sure you will helping as the question which I am about to ask is nothing to the seniors here. My query goes here...
    I have a page called www dot abc dot com and there is some content in that page now I want to store this content in an
    sqlserver.
    I heard that it can be achieved using DOM can you guys help in this. If not in DOM please suggest me the possible ways.
    You CANNOT store "www dot abc dot com " any where because that is a site, not data.
    So FIRST you must first get the data from that site. How you do that depends on the site and the data you want. This might be a trivial step or in might be very, very complicated. This step has nothing to do with storing anything.
    If the sight is VERY simple or you have NO need to store images then you might end up with a single html string which can be stored. However that is very unlikely. If not then you must retrieve all of the different parts from the site, and determine how you want to store those parts. A simple mechanism would be to store the tree (because an extracted html site is going to be representable that way.)
    SECOND then you determine how you want to store it. Unless the page is very simple or you extract almost nothing from the page then you would need to either create an significant data structure in the database or you would need to store the entire tree as a blob. Doing that requires that you convert the tree into a single binary format and then store it. You can google for example for storing retrieving blobs.
    Finally you presumably have researched exactly what your legal right is to download the contents of that site and store it. Even if you own the site there might be limitations on the content (such as picitures) that disallow you from storing it.

  • Download byte code to record store and more?

    How can i download extra byte code (than the jar byte code) to the record store & then execute it?
    Also,i have an Image in server & want to download it to record store...how can i do this?Also,how can i set the wtk1.0.4 so i can download this image for testing?
    Please help! Thanks.

    You can't download extra byte code and then execute it ...
    (you can't not do any class loader trick too because of J2ME restrictions)
    But you can download an image and store it thanks to RMS. It as been described a lot in this forum. get the strem, store the bytes in an array and put it into a Record.
    Regards.

  • SQLServer JDBC data types

    Hi there, I'm trying to store some files in a SQLServer database and I'm facing some problems.
    The thing is: I get a multipart request from a JSP (with a submitted file) and I'm using o'reillys multipart request:
    MultipartParser parser = new MultipartParser(request,10*1024);
    Part part= parser.readNextPart();
    if (part.isFile())
         String filename = ((FilePart)part).getFileName();
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ((FilePart)part).writeTo(baos);
         byte [] ba = baos.toByteArray();
         PreparedStatement ps = c.prepareStatement(SET_CONTENT);
         ByteArrayInputStream bais = new ByteArrayInputStream(b) ;
            ps.setBinaryStream(1,bais,b.length);
         ps.setInt(2,pkid);
         ps.executeUpdate();               
    }I've cut some steps but I think this will give you an ideia of what I'm doing. The field that receives the binary data is defined as "varbinary" (in the database)
    When I run it I get the exception "String or binary data would be truncated."
    I'm kind of stuck here, so I'd appreciate any help. Thanks in advance.

    i am not sure how it works in SQL server..but seeing the error message u wrote ,i doubt it is some thing to do with the field length.
    check at..
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sqlce/htm/_lce_accessing_data.asp
    and
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adminsql/ad_impt_bcp_1vqg.asp
    also try closing the io streams like.
    filePart.getInputStream().close();
    outStream.close();
    good luck.

  • How to find the last element of a byte array

    Dear all,
    I have a byte array with a max lenght of 1024*50 bytes. In that array I store the bytes read from a file. How can I find where the array ends (i.e. which is the last valid element of the byte array)?
    Thank you for your help.
    Best Regards,
    JIM

    I want to send files over TCP connection using BufferedOutputStreams and BufferedInputStreams. The first side (e.g. the client) sends a file (e.g mp3 file or jpeg image) to the server using the code
      public void sendFile(Socket s, String FileName) throws Exception
              BufferedOutputStream out = new BufferedOutputStream(s.getOutputStream());  
              BufferedInputStream in = new BufferedInputStream(new FileInputStream(FileName));
              int len = 0;
              while ( (len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
              in.close();
              out.flush();
            }(The client does not close the BufferedOutputStream out because other files will be sent afterwards)
    Then, the server receives the file using the code:
            public void receiveFile(Socket s, String FileName) throws Exception
              OutputStream out = new BufferedOutputStream(new FileOutputStream(FileName)); 
              InputStream in = new BufferedInputStream(s.getInputStream());
              int len = 0;
              while ( (len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
                break;
              out.flush();
              out.close();
            }(likewise the InputStream in is not closed for the same reasons).
    In order the server to receive the file and stop reading the BufferedInputStream, I will have to make some modifications to this part of the code,
    while ( (len = in.read(buffer)) > 0)so as to know when the whole file has been received.
    Thus, even if I send the length of each file, I will not be able to read it. Could you please recommend me a solution?

  • Suggest double byte characters

    Hello,
    I am running one concurrent program that generates output
    In the output china characters are coming i want to replace with the double byte characters.
    Thanks in advance
    Cheers.

    I think it's pretty standard to use varchar2 for this. I've never heard of anyone wanting to store double-byte character data as a NUMBER. What advantages could you imagine in such a scheme?
    Justin

  • Double Byte Characters

    Which is better: store double byte characters (from other rdbms) as NUMBER or VARCHAR2?
    thanks in advance to those who will reply

    I think it's pretty standard to use varchar2 for this. I've never heard of anyone wanting to store double-byte character data as a NUMBER. What advantages could you imagine in such a scheme?
    Justin

  • XMLStreamReader byte location missmatch

    Hello,
    I am trying to parse a XML file and want to store the byte positions of start and closing tags so I can later use RandomAccessFile to get a particular xml element.
    This should be used to access very big xml files. I want to be able to pull out a arbitrary xml element given only the xpath expression from the root element.
    But I am having some trouble with it.
    I tried to use XMLStreamReader to parse the XML and getLocation to get the byte offset, but the position I get when a START_ELEMENT event occurs is not the start of the XML tag! It is somewhere after that. I have even tried to use the previous or next positions, but none of them fits the start tag.
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(is);
    while ( xsr.hasNext() ) {
        if (xsr.isStartElement()) {
            int currentPos = xsr.getLocation().getCharacterOffset();
            System.out.print("current position: " + currentPos);
    }It would be very helpful if somebody could give me a hint as how to solve my problem or where to find a better way to do this.
    Thanks a lot!

    I tried some more and it seems that the position of the XMLEvent changes when the layout of the XML changes.
    For example using the same code to retrieve the byte positions of a specific tag, I get different results.
    Test XMl files:
    XML 1:
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <first>
      <second>
        <third>
          <forth>Text1a</forth>
          <forth>Text1b</forth>
          <forth>Text1c</forth>
        </third>
      </second>
      <second>
        <third>Text2</third>
      </second>
    </first>XML 2 (same XML, but unformated):
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?><first><second><third><forth>Text1a</forth><forth>Text1b</forth><forth>Text1c</forth></third></second><second><third>Text2</third></second></first>When querying the positions for the start and stop tags of the first occurrence of the "forth" element and then using RandomAccessFile to read in those positions, I get the following results:
    XML1:
    "<forth>Text1a</forth>"
    XML2:
    "th>Text1a</forth><fort"
    I would have expected that the layout of the XML file has no impact.
    Is this a bug or can anybody explain what I must have overlooked?
    Thanks!

  • Multi-byte character

    If DATABASE CHARACTER SET is UTF-8 than
    Than can i use VARCHAR2 to store multi-byte character or i still have to use
    nvarchar2
    also vachar2(1),nvarchar2(1) can store how much (max) bytes in case of UTF-8 CHARACTER SET

    If you create VARCHAR2(1) then you possibly can not store anything as your first character might be multibyte.
    My recommendation would be to consider defining by character rather than by byte.
    CREATE TABLE tbyte (
    testcol VARCHAR2(20));
    CREATE TABLE tchar (
    testcol VARCHAR2(20 CHAR));The second will always hold 20 characters without regard to the byte count.
    Demos here:
    http://www.morganslibrary.org/library.html

  • Byte[] serialization/deserialization BLOB problem

    I want to store an image in DB.
    I choose to store a byte[], like a BLOB (i use MySql).
    But when byte[] is serialized in DB in front of the array are inserted 27
    bytes.
    What should i do to store exact the given byte array ?
    (Or off course an ImageIcon object : for which on deserialization an
    ClassCastException is thrown).
    And which is the reason that those 27 (!?!) bytes are inserted.
    thank you in advance for your help.
    (please excuse my english)
    BytesTest.jdo
    <?xml version="1.0"?>
    <!DOCTYPE jdo SYSTEM "http://www.solarmetric.com/dtds/jdo.dtd">
    <!-- This JDO Metadata file was auto-generated on 7/2/02 3:18 PM.
    See http://www.solarmetric.com for Kodo JDO Documentation and examples. -->
    <jdo>
    <package name="jdoproject">
    <class name="BytesTest" requires-extent="true">
    <field name="bytesArray" null-value="none" primary-key="false">
    <extension key="blob" value="true" vendor-name="kodo"/>
    </field>
    </class>
    </package>
    </jdo>
    BytesTest.java
    package jdoproject;
    public class BytesTest {
    private byte[] bytesArray = null;
    public BytesTest () {
    bytesArray = new byte[30];
    for (int i = 0; i < 30; i++)
    bytesArray[i] = (byte)(65 + i);
    public String toString () {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < bytesArray.length; i++)
    sb.append(" " + (bytesArray[i] & 0xFF) + "[" +
    (char)(bytesArray[i] & 0xFF)
    + "]");
    return sb.toString();
    this must be run twice (first , to make an insertion , second to view what
    is previos inserted)
    BytesTestMain.java
    public class BytesTestMain {
    public static void main (String[] args) {
    BytesTest test = null;
    try {
    JDBCConfiguration jc = new JDBCPropertiesConfiguration();
    PersistenceManagerFactory pmf = new
    JDBCPersistenceManagerFactory(
    new FileInputStream("config/kodo.properties"));
    PersistenceManager pm = pmf.getPersistenceManager();
    Extent people = pm.getExtent(BytesTest.class, false);
    Query query = pm.newQuery(BytesTest.class, people);
    Collection result = (Collection)query.execute();
    Iterator iter = result.iterator();
    System.out.println("Found items: ");
    while (iter.hasNext()) {
    test = (BytesTest)iter.next();
    System.out.println("test= " + test);
    test = new BytesTest();
    System.out.println("Inserting item: "+test);
    Transaction t = pm.currentTransaction();
    t.begin();
    pm.makePersistent(test);
    t.commit();
    } catch (Exception e) {
    e.printStackTrace();
    System.out.println("ALL DONE---------------------");

    cross-post:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=323525

  • Floating point number to IBM bytes

    Hello,
    I'm trying to convert a float value to a byte array (but in IBM standard).
    I understand that the general idea will be the following algorithm:
    1. process the sign, exponent and fraction from the float value (using IBM standard)
    2. build the bytes from the S, E, F from step 1.
    So far, I only have the step 2 like this:
    public static byte[] toBytesIbm( int signBit, int exponent, long fraction ) {
    byte[] bytes = new byte[4];
    bytes[0] = (byte)(signBit + exponent);
    bytes[1] = (byte)((fraction & 0x00FF0000) >> 16);
    bytes[2] = (byte)((fraction & 0x0000FF00) >> 8);
    bytes[3] = (byte)(fraction & 0x000000FF);
    return bytes;
    Getting the sing bit is also not a problem, so the real work is in getting the exponent and fraction from the number. I don't know how to do this. I have code from a trusted source to convert from IBM bytes to IEEE float numbers, so I can check if the bytes are correct.
    Can anyone help me with this?
    Thanks in advance

    Brushfire wrote:
    Thanks for the correct. I'm never quite sure about the masks, but I've had issues with extra data being introduced before, so I like it better safe than sorry. The mask is needed when a narrower primitive has been sign-extended to a wider primitive, and you want to keep the result unsigned.
    But in this case, the result is then cast to byte, which removes all the upper bits that the mask was trying to set to zero in the first place.
    If you need to store a byte in an int without sign-extension, you need a mask:
    int n = someByte & 0xFF;If you want to store the lower 8 bits of an int in another int, you need a mask:
    int lowerEight = someInt & 0xFF;But if you want to store the lower 8 bits in a byte, just cast:
    byte lowerEight = (byte)someInt;

  • 2004s file download (how to not store files in context?)

    Hi,
    I want to use FileDownload element in my web dynpro application.
    I use the new type resource  and my own input source implementation, which generates files on the fly.
    Each download call should result in a new file. These files can be very large (some MB).
    For obvious reasons I don't want the server to store the byte data in application context (200 users * 2 MB ....)
    How can I do this?
    If I use resource as context element and set debug points on my input stream, I can see the data is read just on time if the user wants to download.
    I create my data in my inputstream and the download starts. So far so good.
    On the second click on the download link the download starts without any read operation. Thats the problem.
    Possible reasons:
    First: the data is read and stored to the context on the first download. this would be bad! context would get very very large. not working for me.
    second: the browser or the server caches the data. how can I avoid this?
    thx in advance
    btw I read a tutorial about up and downloading. this pointed to an additional article called something like "downloading in web dynpro tables". But I can't find it. There the on demand downloading should be explained. any help would be great.

    Hallo Thomas,
    ok, the "default" on-demand streaming solution caches a Web Resource but does not re-calculate it again afterwards.
    I wrote a Wiki Code Tutorial which demonstrates how to download an Excel File from a Web Dynpro table UI element on-demand. In this scenario the resource must also be re-created on every request. The solution is based on re-initializing the context with a new  0-byte resource objects within the calculated context attribute getter method.
    See <a href="https://wiki.sdn.sap.com/wiki/display/Snippets/ExportingTableDatainWebDynproJava-SAPNetWeaver04s">Exporting Table Data in Web Dynpro Java - SAP NetWeaver 04s</a>
    For you the most important line of code in
    //@@begin javadoc:getExcelResourceOnDemStreamCalc(IPrivateExcelExportComp.IExcelElement)
       *  Declared getter method for attribute ResourceOnDemStreamCalc of node ExcelResource
       *  @param element the element requested for the value
       *  @return the calculated value for attribute ResourceOnDemStreamCalc
      //@@end
      public com.sap.tc.webdynpro.progmodel.api.IWDInputStream getExcelResourceOnDemStreamCalc(IPrivateExcelExportComp.IExcelElement element)
        //@@begin getExcelResourceOnDemStreamCalc(IPrivateExcelExportComp.IExcelElement)
        IWDInputStream excelOnDemandStream = null;
        try {
          excelOnDemandStream =
            WDResourceFactory.createInputStream(toExcel(tableDataNode, tableColumnInfos).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
          wdComponentAPI.getMessageManager().reportException(e.getLocalizedMessage(), true);
        // Reset context attribute 'Excel.Resource' again by creating a new 0-byte resource object.
        // Otherwise the on-demand Excel stream gets calculated only once as the resource object,
        // cached in the Web Dynpro Binary Cache on server-side, keeps the same.
        initializeOnDemandExcelResource();
        // Return excel on-demand input stream
        return excelOnDemandStream;
        //@@end
    is the method <b>call initializedOnDemandExcelResource()</b> re-initializing the context attribute with a new 0-byte resource object.
    //@@begin others
      //======= Private Methods ===========================
       * Create new on-demand resource instance for excel file. This method must be
       * invoked initially and in the calculated context attribute getter method (calculating)
       * the excel resource input stream. Otherwise the resource is streamed to the client only
       * once but not afterwards so that later updates of the table data are not reflected in the
       * streamed Excel file.
       * URL is stored in context so context in client component can map to it.
      private void initializeOnDemandExcelResource() {
        excel0ByteResource =
          WDResourceFactory.createResource(calcAttrPointer, "Table.xls", WDWebResourceType.XLS);
        excelResourceElement.setResource(excel0ByteResource);
        excelResourceElement.setResourceURL(
          excel0ByteResource.getUrl(WDFileDownloadBehaviour.OPEN_INPLACE.ordinal()));
    Regards, Bertram

Maybe you are looking for