Prepared Statment or Hibernate

I will query One Column in a Table..
Is there any difference between Prepared Statment and Hibernate when it comes to performance?

923269 wrote:
Can I use H-SQL of Hibernate?HSQL is the query language that Hibernate defines to allow you to ask questions about your model (entity classes) in stead of having to write SQL which is oriented towards databases. Hibernate is responsible for translating the HSQL query to an actual SQL query and translate the results back to an object model structure.
So yes you can use HSQL, IF you use Hibernate.

Similar Messages

  • JSP MySql prepared statments :(

    Hi all - absolute newbie here! - I want to use a prepared statment to search a database based on date - I can get the dates into the database fine but no can get out!
    this is the error I get with most the code below
    org.apache.jasper.JasperException: Syntax error or access violation, message from server: "You have an error in your SQL syntax near '?' at line 1"
    <%@ page import="java.sql.*, java.util.*, java.lang.*" %>
    <%
    String fromDate=request.getParameter("fromDate");
    String toDate=request.getParameter("toDate");
    String myYear=(fromDate.substring(6,10));
    String myMonth=(fromDate.substring(3,5));
    String myDay=(fromDate.substring(0,2));
    String myDate=(myYear myMonth myDay);
    int myNewDate=Integer.parseInt(myDate);
    Connection con = null;
    try
    String DBUrl="jdbc:mysql://database";
    String user="user";
    String password="pass";
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();     
         con = DriverManager.getConnection(DBUrl,user,password);
         String sql= "select * from caryard where enquiryDate=?";
         PreparedStatement st = con.prepareStatement(sql);
         st.setInt(1,myNewDate);
         st.executeQuery(sql);
    any help would be much appreciated
    Vix with almost no hair left               

    First thing I see is that you are creating an int for the DATE you are trying to query. I'm not too familiar with MySql, but I'm sure that if you create a field in the database to hold dates then you would have to create a Date object, or Calendar object and then use that to query to database. Plus, the date cannot be read as 20021105 from the database.
    I'd look into that first, and make sure the about the datatype you are trying to access in MySql and then also make sure that you have to create Calendar (new GregorianCalendar(year, month, date)) in order to access that db field.
    Good luck

  • Prepared statments error

    i have this error for my preparedstatments
    exception in dbMember.createPreparedStatements() : String index out of range : 0
    what does it means?
    i am trying to call my selectMemMaxID function to retrieve the max id from my member table
    this is my selectMemMaxID method
    public void selectMemMaxId() throws Exception
              try{
                   ResultSet rs = selectMaxIdPstmtMem.executeQuery();
                   setMemMaxId(rs.getInt(1));
                   catch (SQLException e)
                        System.out.println("SQLException thrown" + e.getMessage());
    and this is my createPreparedStatments() method
         public void createPreparedStatements()
              try
    //For select Max Id in memberparticular table
                   selectMaxIdStrMem = "select max(memparticular_memid) as MaxId from memberparticular";
                   selectMaxIdPstmtMem = dbConn.createPreparedStatement(selectMaxIdStrMem);
              catch (Exception e)
    System.out.println("Exception in dbMember.createPreparedStatements() : " + e.getMessage() );

    i did try doing that
    public void selectMemMaxId() throws Exception
              try{
                   ResultSet rs = selectMaxIdPstmtMem.executeQuery();
              while (rs.next())
                   setMemMaxId(rs.getInt(1));
                   catch (SQLException e)
                        System.out.println("SQLException thrown" + e.getMessage());
    but it still return me a java.lang.NullPointerException error and
    the error i stated above

  • Pass table name as parameter in prepared Statement

    Can I pass table name as parameter in prepared Statement
    for example
    select * from ? where name =?
    when i use setString method for passing parameters this method append single colon before and after of this parameter but table name should be send with out colon as SQL Spec.
    I have another way to make sql query in programing but i have a case where i have limitation of that thing so please tell me is it possible with prepared Statment SetXXx methods or not ?
    Thanks
    Haroon Idrees.

    haroonob wrote:
    I know ? is use for data only my question is this way to pass table name as parameterI assume you mean "how can I do it?" As I have already answered "is this the way?" with no.
    Well, I would say (ugly as it is) String concatenation, or stored procedures.

  • Set char in Prepared Statement

    Hi,
    Can any one let me know how to set Character value in Prepared Statement. I have my table in which the column is of Char type. Now in my prepared statment, I am saying
    PreparedStament pstmt = con.prepareStatement("select ticker from INSTRUMENT_TICKERXREF where ticker = ? ");
    pstmt.setString(1,'F');
    I even tried pstmt.setString(1,"F");
    It gives me incompatible types. Can any please help me on this asap.
    Regards,
    ..Raj

    Hi,
    I just tried using setString(), it does not seem to give any problems. But in any case, you could use setObject() too.
    I tried both setString() and setObject for an example table structure as below:
    create table testchar(col1 CHAR(3));
    insert into testchar('one');
    from java class:
    PreparedStatement pstmt = conn.prepareStatement("select col1 from testchar where col1 = ? ");
    //pstmt.setObject(1,"one");
    pstmt.setString(1,"one");
    Hope that helps.
    Savitha.
    OTN group@IDC

  • Statment used like PreparedStatement

    following is the code of a DAO written by one of the team member. He says that PreparedStatements are slower and so he is writing DAO using Statements. For queries which takes dynamic parameters this code uses a StringUtil class to parse queries and replce all '?' with parameters. I am posting StringUtils class with this code. I request you to send suggestions on this design. I feel this will be slower than using PreparedStatement.
    //Standard JDK imports
    import java.util.Collection;
    import java.util.HashMap;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import com.nate.common.NATEConnection;
    import com.nate.common.exception.DAOException;
    import com.nate.common.exception.NATEConnectionException;
    import com.nate.common.utils.StringUtils;
    import com.nate.web.admin.admusrmgmt.vo.AdminMgmtVO;
    //3rd Party imports
    import org.apache.log4j.Logger;
    public class AdminMgmtDAO
         private NATEConnection m_nateCon;
         private final static String CREATE_ADMIN_QUERY =
              "INSERT INTO ADMIN_USER (USER_ID, "
                   + "USER_ROLE,CREATE_DATE,USE_YN, USER_PHONE,PASSWORD,"
                   + "USER_NAME, HOME_ADDRESS) "
                   + "VALUES (?,'admin',sysdate,?,?,?,?,? )";
         private static final String FIND_ADMIN_BY_ADMINNAME_QUERY =
              "SELECT USE_YN, USER_PHONE, PASSWORD, USER_NAME, "
                   + "HOME_ADDRESS FROM ADMIN_USER WHERE USER_NAME=?";
         /** Logger, used to log messages */
         private Logger m_logger = Logger.getLogger(AdminMgmtDAO.class);
         private final static String LS = System.getProperty("line.separator");
         public AdminMgmtDAO()
              m_nateCon = new NATEConnection();
              m_logger.info("NATE Connection object created");
         public void createAdmin(AdminMgmtVO vo) throws DAOException
              Connection con = null;
              Statement stmt = null;
              try
                   //Example using the StringUtils + Statement classes for CUD operation
                   con = m_nateCon.getConnection();
                   stmt = con.createStatement();
                   StringUtils utils = new StringUtils(CREATE_ADMIN_QUERY);
                   utils.setString(1, vo.getAdminID());
                   utils.setString(2, vo.getStatus());
                   utils.setString(3, vo.getMobileNumber());
                   utils.setString(4, vo.getAdminPassword());
                   utils.setString(5, vo.getAdminName());
                   utils.setString(6, vo.getHomeAddress());
                   String sQuery = StringUtils.getQueryString();
                   if (m_logger.isInfoEnabled())
                        StringBuffer sbBuffer = new StringBuffer(50);
                        sbBuffer.append("Creating Admin user using Query").append(LS);
                        sbBuffer.append(sQuery).append(LS);
                        m_logger.info(sbBuffer.toString());
                   stmt.execute(sQuery);
              catch (NATEConnectionException ex)
                   String strErrMsg =
                        "[Unable to get the Connection from the NATEConnection Class]";
                   m_logger.error(strErrMsg, ex);
                   throw new DAOException(strErrMsg, ex);
              catch (SQLException ex)
                   String strErrMsg = "[Unable to create the Prepared Statment]";
                   m_logger.error(strErrMsg, ex);
                   throw new DAOException(strErrMsg, ex);
              finally
                   try
                        if (stmt != null)
                             stmt.close();
                        if (con != null)
                             con.close();
                   catch (SQLException ex)
                        String strErrMsg = "[Unable to close the Resources]";
                        m_logger.error(strErrMsg, ex);
         } //end of createAdmin
         public Collection findByAdminName(String adminName) throws DAOException
              Connection con = null;
              Statement stmt = null;
              ResultSet rSet = null;
              AdminMgmtVO vo = null;
              Collection result = null; //result sent to client
              //Example using the StringUtils + Statement classes for Read operation
              try
                   con = m_nateCon.getConnection();
                   stmt = con.createStatement();
                   StringUtils utils = new StringUtils(FIND_ADMIN_BY_ADMINNAME_QUERY);
                   utils.setString(1, "%" + adminName + "%");
                   String sQuery = StringUtils.getQueryString();
                   if (m_logger.isInfoEnabled())
                        m_logger.info(
                             "Query performing search :" + sQuery);
                   rSet = pStmt.executeQuery();
                   while (rSet.next())
                        if (result == null)
                             result = new ArrayList();
                        vo = new AdminMgmtVO();
                        vo.setStatus(rSet.getString("USE_YN"));
                        vo.setMobileNumber(rSet.getString("USER_PHONE"));
                        vo.setAdminPassword(rSet.getString("PASSWORD"));
                        vo.setAdminName(rSet.getString("USER_NAME"));
                        vo.setHomeAddress(rSet.getString("HOME_ADDRESS"));
                        result.add(vo);
                        vo = null;
              catch (NATEConnectionException e)
                   String strErrMsg =
                        "[Unable to get the Connection from the NATEConnection Class]";
                   m_logger.error(strErrMsg, e);
                   throw new DAOException(strErrMsg, e);
              catch (SQLException e)
                   String strErrMsg = "[Unable to create the Prepared Statment]";
                   m_logger.error(strErrMsg, e);
                   throw new DAOException(strErrMsg, e);
              finally
                   try
                        if (rSet != null)
                             rSet.close();
                        if (stmt != null)
                             stmt.close();
                        if (con != null)
                             con.close();
                   catch (SQLException e)
                        String strErrMsg = "[Unable to close the Resources]";
                        m_logger.error(strErrMsg, e);
              return result;
         } //end of findByAdminName
    } //end of class
    package com.nate.common.utils;
    import com.nate.common.utils.exception.NotEnoughArgumentsException;
    import com.nate.common.utils.exception.TooManyArgumentsException;
    import java.io.PrintStream;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class StringUtils
        public StringUtils(String s)
            m_sQueryStr = s;
            parseString(m_sQueryStr);
            m_argMap = new HashMap();
        public String replaceAll(String s, String s1, String s2)
            String s3 = s;
            Pattern pattern = Pattern.compile(s1);
            Matcher matcher = pattern.matcher(s3);
            return matcher.replaceAll(s2);
        public void setString(int i, String s)
            throws IllegalArgumentException
            if(i > m_map.size())
                throw new IllegalArgumentException();
            int j = s.indexOf("'");
            String s1;
            if(j > 0)
                s1 = replaceAll(s, "'", "''");
            else
                s1 = s;
            m_argMap.put(new Integer(i), s1);
        public void setInt(int i, int j)
            throws IllegalArgumentException
            if(i > m_map.size())
                throw new IllegalArgumentException();
            } else
                m_argMap.put(new Integer(i), String.valueOf(j));
                return;
        public void setLong(int i, int j)
            throws IllegalArgumentException
            if(i > m_map.size())
                throw new IllegalArgumentException();
            } else
                m_argMap.put(new Integer(i), String.valueOf(j));
                return;
        private void parseString(String s)
            int i = 0;
            int j = 0;
            for(i++; i < s.length(); i++)
                char c = s.charAt(i);
                if(c != '?')
                    continue;
                if(m_map == null)
                    m_map = new HashMap();
                m_map.put(new Integer(++j), new Integer(i));
        public void clearParameters()
            m_argMap.clear();
        public StringBuffer getQueryString()
            throws NotEnoughArgumentsException, TooManyArgumentsException
            StringBuffer stringbuffer = new StringBuffer();
            int i = m_map.size();
            int j = m_argMap.size();
            if(j < i)
                throw new NotEnoughArgumentsException();
            if(j > i)
                throw new TooManyArgumentsException();
            int k = 0;
            for(int l = 1; l < i + 1; l++)
                int i1 = ((Integer)m_map.get(new Integer(l))).intValue();
                stringbuffer.append(m_sQueryStr.substring(k, i1));
                stringbuffer.append("'");
                stringbuffer.append(m_argMap.get(new Integer(l)));
                stringbuffer.append("'");
                k = ++i1;
            if(k < m_sQueryStr.length())
                stringbuffer.append(m_sQueryStr.substring(k, m_sQueryStr.length()));
            return stringbuffer;
        public static void main(String args[])
            StringUtils stringutils = new StringUtils("INSERT INTO ADMIN_USER (USER_ID, USER_ROLE,CREATE_DATE,USE_YN, AGE) VALUES (?,'admin',sysdate,?,?)");
            stringutils.setString(1, "test");
            stringutils.setString(2, "Y");
            stringutils.setInt(3, 25);
            System.out.println(stringutils.getQueryString());
            stringutils.clearParameters();
            stringutils.setString(1, "abc'd");
            stringutils.setString(2, "N");
            stringutils.setInt(3, 30);
            System.out.println(stringutils.getQueryString());
            stringutils.setString(1, "%xyz%");
            System.out.println(stringutils.getQueryString());
        private String m_sQueryStr;
        private Map m_map;
        private Map m_argMap;
    }

    As you noticed, the order in which you measure Statement and PreparedStatement matters. This is because all the JDBC driver libraries and standard JDK classes get JIT compiled at the start of the run. The timings are not showing the speed of your code, they are showing the speed of JIT compilation.
    When doing microbenchmarking, run the measured code several times in a loop. The first few loops are likely to be slower as the JIT compiler is running; then timings more or less settle.
    Below is a simple comparision of Statement and PreparedStatement. I won't keep you in suspense: there is no difference under Oracle. "PS's are slow" is a myth.
    Other database servers may differ, so if you are executing lots of small SQL statements in tight time-critical loops, benchmark first, then decide which type of statement to use. (PS's most likely, because you can keep them open and re-use them.)
    If you have big SQL statements, ask yourself: does the difference between a Statement and a PS really matter? If the db server takes a second to execute the query, and the difference is a few milliseconds, wasting time optimizing it is really silly. Especially given the convenience, safety, and portability of not having to do string quoting and date/time formatting yourself.
    // java demo jdbc:oracle:thin:@dbserver:port:dbname username password
    import java.sql.DriverManager;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    public class demo
        static Connection connection;
        static int ROUNDS = 100;
        public static void main(String args[])
         try {
             DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
             connection = DriverManager.getConnection(args[0], args[1], args[2]);
             long best;
             best = -1;
             for (int n = 0; n < 10; n++) {
              long time = staticStatement();
              if (best == -1 || time < best)
                  best = time;
             System.out.println("best time " + best);
             best = -1;
             for (int n = 0; n < 10; n++) {
              long time = staticPrepared();
              if (best == -1 || time < best)
                  best = time;
             System.out.println("best time " + best);
             best = -1;
             for (int n = 0; n < 10; n++) {
              long time = plainStatement();
              if (best == -1 || time < best)
                  best = time;
             System.out.println("best time " + best);
             best = -1;
             for (int n = 0; n < 10; n++) {
              long time = plainPrepared();
              if (best == -1 || time < best)
                  best = time;
             System.out.println("best time " + best);
             best = -1;
             for (int n = 0; n < 10; n++) {
              long time = reuseStatement();
              if (best == -1 || time < best)
                  best = time;
             System.out.println("best time " + best);
             best = -1;
             for (int n = 0; n < 10; n++) {
              long time = reusePrepared();
              if (best == -1 || time < best)
                  best = time;
             System.out.println("best time " + best);
         } catch (Exception e) {
             System.err.println("exception in db test: " + e);
             e.printStackTrace(System.err);
        private static long staticStatement()
         throws SQLException
         long start_time = System.currentTimeMillis();
         for (int n = 0; n < ROUNDS; n++) {
             String sql = "select 42 from dual";
             Statement stmt = connection.createStatement();
             ResultSet res = stmt.executeQuery(sql);
             while (res.next()) {
              int result = res.getInt(1);
             Util.close(res);
             Util.close(stmt);
         long end_time = System.currentTimeMillis();
         long time = end_time - start_time;
         System.out.println("static statement: " + time + " ms");
         return time;
        private static long staticPrepared()
         throws SQLException
         long start_time = System.currentTimeMillis();
         for (int n = 0; n < ROUNDS; n++) {
             String sql = "select 42 from dual";
             PreparedStatement stmt = connection.prepareStatement(sql);
             ResultSet res = stmt.executeQuery();
             while (res.next()) {
              int result = res.getInt(1);
             Util.close(res);
             Util.close(stmt);
         long end_time = System.currentTimeMillis();
         long time = end_time - start_time;
         System.out.println("static prepared: " + time + " ms");
         return time;
        private static long plainStatement()
         throws SQLException
         long start_time = System.currentTimeMillis();
         for (int n = 0; n < ROUNDS; n++) {
             String sql = "select " + n + " from dual";
             Statement stmt = connection.createStatement();
             ResultSet res = stmt.executeQuery(sql);
             while (res.next()) {
              int result = res.getInt(1);
             Util.close(res);
             Util.close(stmt);
         long end_time = System.currentTimeMillis();
         long time = end_time - start_time;
         System.out.println("plain statement: " + time + " ms");
         return time;
        private static long plainPrepared()
         throws SQLException
         long start_time = System.currentTimeMillis();
         for (int n = 0; n < ROUNDS; n++) {
             String sql = "select ? from dual";
             PreparedStatement stmt = connection.prepareStatement(sql);
             stmt.setInt(1, n);
             ResultSet res = stmt.executeQuery();
             while (res.next()) {
              int result = res.getInt(1);
             Util.close(res);
             Util.close(stmt);
         long end_time = System.currentTimeMillis();
         long time = end_time - start_time;
         System.out.println("plain prepared: " + time + " ms");
         return time;
        private static long reuseStatement()
         throws SQLException
         long start_time = System.currentTimeMillis();
         Statement stmt = connection.createStatement();
         for (int n = 0; n < ROUNDS; n++) {
             String sql = "select " + n + " from dual";
             ResultSet res = stmt.executeQuery(sql);
             while (res.next()) {
              int result = res.getInt(1);
             Util.close(res);
         Util.close(stmt);
         long end_time = System.currentTimeMillis();
         long time = end_time - start_time;
         System.out.println("reuse statement: " + time + " ms");
         return time;
        private static long reusePrepared()
         throws SQLException
         long start_time = System.currentTimeMillis();
         String sql = "select ? from dual";
         PreparedStatement stmt = connection.prepareStatement(sql);
         for (int n = 0; n < ROUNDS; n++) {
             stmt.setInt(1, n);
             ResultSet res = stmt.executeQuery();
             while (res.next()) {
              int result = res.getInt(1);
             Util.close(res);
         Util.close(stmt);
         long end_time = System.currentTimeMillis();
         long time = end_time - start_time;
         System.out.println("reuse prepared: " + time + " ms");
         return time;
        public static class Util
         public static void close(Statement s)
             if (s == null)
              return;
             try {
              s.close();
             } catch (Exception e) {
              System.err.println("Util.close: error closing Statement: " + e);
         public static void close(ResultSet s)
             if (s == null)
              return;
             try {
              s.close();
             } catch (Exception e) {
              System.err.println("Util.close: error closing ResultSet: " + e);

  • MS SQL Server 7 - Performance of Prepared Statements and Stored Procedures

    Hello All,
    Our team is currently tuning an application running on WL 5.1 SP 10 with a MS
    SQL Server 7 DB that it accesses via the WebLogic jConnect drivers. The application
    uses Prepared Statements for all types of database operations (selects, updates,
    inserts, etc.) and we have noticed that a great deal of the DB host's resources
    are consumed by the parsing of these statements. Our thought was to convert many
    of these Prepared Statements to Stored Procedures with the idea that the parsing
    overhead would be eliminated. In spite of all this, I have read that because
    of the way that the jConnect drivers are implemented for MS SQL Server, Prepared
    Statments are actually SLOWER than straight SQL because of the way that parameter
    values are converted. Does this also apply to Stored Procedures??? If anyone
    can give me an answer, it would be greatly appreciated.
    Thanks in advance!

    Joseph Weinstein <[email protected]> wrote:
    >
    >
    Matt wrote:
    Hello All,
    Our team is currently tuning an application running on WL 5.1 SP 10with a MS
    SQL Server 7 DB that it accesses via the WebLogic jConnect drivers.The application
    uses Prepared Statements for all types of database operations (selects,updates,
    inserts, etc.) and we have noticed that a great deal of the DB host'sresources
    are consumed by the parsing of these statements. Our thought was toconvert many
    of these Prepared Statements to Stored Procedures with the idea thatthe parsing
    overhead would be eliminated. In spite of all this, I have read thatbecause
    of the way that the jConnect drivers are implemented for MS SQL Server,Prepared
    Statments are actually SLOWER than straight SQL because of the waythat parameter
    values are converted. Does this also apply to Stored Procedures???If anyone
    can give me an answer, it would be greatly appreciated.
    Thanks in advance!Hi. Stored procedures may help, but you can also try MS's new free type-4
    driver,
    which does use DBMS optimizations to make PreparedStatements run faster.
    Joe
    Thanks Joe! I also wanted to know if setting the statement cache (assuming that
    this feature is available in WL 5.1 SP 10) will give a boost for both Prepared Statements
    and stored procs called via Callable Statements. Pretty much all of the Prepared
    Statements that we are replacing are executed from entity bean transactions.
    Thanks again

  • Performance of Stored procedures against Prepared Statements

    What will be the exact difference in the performance between implementing stored procedures and prepared statements ?

    Short answer: it depends.
    There will probobaly be very little difference in performance difference for a sipmle insert / update etc.
    Multiple inserts / updates etc you will probobaly find faster with a stored procedure rather than n prepared statments as you only have to contact the database once vs n times.
    Hope this helps!

  • X200 cannot sleep/hibernate after WWAN has been used

    Since upgrading to Windows 7 I experience problem using Sleep or Hibernate.
    If I have been using WWAN (the Ericsson card) the computer will not Sleep or Hibernate afterwards (sometimes it will work, maybe 1 out of 10 times). The computer will start preparing for Sleep/Hibernate and will switch off the screen. But it never finished (caps lock will not work, but the HD LED can be seen blinking every 3 second or so) and will stay on until the battery is drained or a hard reset is performed.
    It was working ok in the beginning after installing Window 7, but stopped working somes in june/juli this year.
    /MF

    HI, thanks, but I know I can set a new password. I just wanted to get my old one back cos I have used it a long time & can therefore remember it.

  • How do I write an OutputStream to a String?

    I'm using an ObjectOutputStream to serialize a LinkedList. I tried using a ByteArrayOutputStream and invoking the toString() method thereof, but it changes the first two entries in the array and throws off the readObject() method of the ObjectInputStream I'm reading it into. What can I do?

    I'm not 100% sure if this idea will work but you are welcome to try if you are using an Oracle database. There may be better ways to do this, and I believe my answer is depnedent upon having oracle.
    Are you familiar with the LONG RAW datatype in oracle?
    Serialize the object(s) to a file so you have a source for an input stream.
    Create a table with a LONG RAW field.
    Create the row and retrieve the id with a null field for the LONG RAW.
    Create a prepared statment with the long raw field as a parameter.
    Read your file into an input stream into the parameters of the prepared statement as a binary stream (setBinaryStream).
    Update the table for the given id.
    Verfiy your result ( I would reccomend that you use some sort of db tool to just extract the data and do a file comparison between the file you used to insert, and what is retrieved).
    Writing a file to a LONG RAW field (normally you would use BLOB but I have never had much luck with it) is one way that If you wanted to save a file (of any type) to a database that you could do it.
    This process could get a bit tricky, but I will say I have written 4 meg pdf files to a database using it. You may want to do a search on the word blob (although as I said when I attempted to write to a blob in oracle I had problems, I used long raw instead which has a smaller limit to it's size) in the jdbc discussion group for writing a file to a database.
    Hope this might be some help to you.
    Good luck,
    Dan Hughes
    Question one: Why?
    Question two: Then how can I store it in a database?
    Is it even possible?

  • Multiple SQL Update within Parent Query

    I am tring to extract an image from within a MS SQL image field,
    opening the image using JAI, getting the src.getWidth() & src.getHeight
    () of each item within the database, and then writing the width and
    height back into the database. Everything works except when I goto
    write the values into the database - the page (when loading) continues
    to work and work and work until I restart the tomcat service. I do not
    understand why this would occur, and what is even stranger - I have
    very similar code i used for resizing images in the database into a
    thumbnail - display and original file sizes using a similar approach...
    and that works with out a problem...
    I have tried the code with out the inner update query - it works. I
    tried with just the selection of a single specific item in the first
    query and that works, but when I try multiple updates the second query
    appears to stall.
    The code is as follows.:
    <%@ page language="java" import="javax.servlet.*,javax.servlet.http.*,java.io.*,java.util.*,java.sql.*,javax.media.jai.*,java.awt.*,java.awt.image.*,java.awt.Graphics.*,java.awt.geom.*,java.awt.image.renderable.*,javax.media.jai.widget.*,com.jspsmart.upload.*,java.net.*,com.sun.media.jai.codec.*"%>
    <jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
    <%
         // Variables
         int count=0;
         int width                                             = 0;
         int height                                             = 0;
         String vFileName                                   = "";
         String vFileExt                                        = "";
         String vFileID                                        = "";
         String format                                        = "0";
         // Connect to the database
         Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
         Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://206.152.227.62:1433;DatabaseName=WWWBBD;User=wwwbbd;Password=bbd1412");
         //Create the statement
         Statement sqlGetPics                              = con.createStatement();
         Statement sqlUpdate                                   = con.createStatement();
         //build the query
         String qryGetPics                                   = "SELECT TOP 5 FileID, FileExt, FileName, AdjFile = CASE WHEN FullFile IS NULL THEN Display ELSE FullFile END FROM FileStore WHERE (UPPER(FileExt) = '.JPG' OR UPPER(FileExt) = '.TIF' OR UPPER(FileExt) = '.GIF' OR UPPER(FileExt) = '.BMP') AND (NOT Display IS NULL OR NOT FullFile IS NULL)";
         //execute the query
         ResultSet rsGetPics                                   = sqlGetPics.executeQuery(qryGetPics);
         // Initialization
         SmartUpload uploader                              = new SmartUpload();
         uploader.initialize(getServletConfig(),request,response);
         mySmartUpload.initialize(getServletConfig(), request, response);
         // Upload
         mySmartUpload.upload();
         while (rsGetPics.next()) {
              vFileID                                             = rsGetPics.getString("FileID");
              vFileExt                                        = rsGetPics.getString("FileExt");
              vFileName                                        = rsGetPics.getString("FileName") + vFileExt;
              width                                             = 0;
              height                                             = 0;
              uploader.fieldToFile(rsGetPics, "AdjFile", "/upload/" + vFileName);
              if (vFileExt.equalsIgnoreCase(".JPG") || vFileExt.equalsIgnoreCase(".JPEG"))
                   format                                        = "JPEG";
              else if (vFileExt.equalsIgnoreCase(".TIF") || vFileExt.equalsIgnoreCase(".TIFF"))
                   format                                        = "TIFF";
              else if (vFileExt.equalsIgnoreCase(".GIF"))
                   format                                        = "JPEG";
              else if (vFileExt.equalsIgnoreCase(".BMP"))
                   format                                        = "BMP";
              else
                   format                                        = "0";
              // update the width & height
              if (format != "0")
                   try
                        //Opens the image
                        RenderedImage src                    = JAI.create("fileload","d:\\servers\\tomcat\\webapps\\jsp\\upload\\" + vFileName);
                        width                                   = src.getWidth();
                        height                                   = src.getHeight();
                        java.io.File imageFile               = new java.io.File("d:\\servers\\tomcat\\webapps\\jsp\\upload\\" + vFileName);
                        InputStream is                         = new FileInputStream(imageFile);
                        //build the query
                        String qryUpdate                    = "UPDATE FileStore SET Width = " + width + ", Height = " + height + " WHERE FileID = " + vFileID;
                        //execute the query
                        ResultSet rsUpdate                    = sqlUpdate.executeQuery(qryUpdate);
                        %>[<%=width%>x<%=height%>:<%=vFileID%>:<%=qryUpdate%>]<BR><%
                   catch(Exception e)
                        {out.println("An error occurs : " + e.toString());}               
              count++;          
         //rsUpdate.close();
         sqlUpdate.close();
    %>
    <HTML>
    <HEAD>
         <TITLE>Repair Files</TITLE>
    </HEAD>
    <BODY>
    <%=count%> files updated in the database.
    </BODY>
    </HTML>

    BTW - I also tried this with a prepared statment query... no good.

  • PreparedStatment creating Syntax Error.

    The poblem is in the first prepared statment if I enter the value straight into the statement string everying works fine. However, when I use a ? for placeholder and then supply the same sting value i would have entered in the statement string I get a sytax error.
    import java.sql.*; import javax.swing.*; import java.awt.BorderLayout; import java.awt.event.*; public class Exercise34_5 extends JFrame { private JTextField jtfInput = new JTextField(10); private JButton jbShowTable = new JButton("Show Table"); private JTextArea jta = new JTextArea(); private PreparedStatement pstmt1; private PreparedStatement pstmt2; private PreparedStatement pstmt3; public Exercise34_5() { JPanel northPanel = new JPanel(); northPanel.add(new JLabel("Table Name")); northPanel.add(jtfInput); northPanel.add(jbShowTable); add(northPanel, BorderLayout.NORTH); add(new JScrollPane(jta)); try { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/test" , "root", "root"); pstmt1 = connection.prepareStatement("describe ?"); pstmt2 = connection.prepareStatement("select count(*) from enrollment"); pstmt3 = connection.prepareStatement("select * from enrollment"); }catch(Exception ex) { ex.printStackTrace(); } jbShowTable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String table = jtfInput.getText(); try{ pstmt1.setString(1, "enrollment"); /*pstmt2.setString(1, "enrollment"); pstmt3.setString(1, "enrollment");*/ ResultSet rset1 = pstmt1.executeQuery(); ResultSet rset3 = pstmt3.executeQuery(); int count = 0; while(rset1.next()) { jta.append(rset1.getString(1) + "\t"); count++; } jta.append("\n"); System.out.println(count); while(rset3.next()) { for(int i = 1; i <= count; i++) { jta.append(rset3.getString(i) + "\t"); } jta.append("\n"); } }catch(Exception ex) { ex.printStackTrace(); } } }); } public static void main(String[] args) { Exercise34_5 frame = new Exercise34_5(); frame.setSize(400, 200); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setVisible(true); } }
    java.sql.SQLException: Syntax error or access violation message from server: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''enrollment'' at line 1"
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1997)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1167)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1278)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:2251)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1586)
    at Exercise34_5$1.actionPerformed(Exercise34_5.java:47)

    Alyosha wrote:
    I don't understand.You can't just put a ? parameter any old place in a prepared statement. It's just just a simple string substitution. For instance, you cannot use a ? parameter for a table name or a column name.
    // wrong
    ps = conn.prepareStatement("select * from ? where ? = ?");
    ps.setString(1, tableName);
    ps.setString(2, columnName);
    ps.setString(3, columnValue);
    // right
    ps = conn.prepareStatement("select * from " + tableName = " where " + columnName + " = ?");
    ps.setString(1, columnValue);

  • Missing operator in query expression (Help)

    Hi I'm trying to implement "OR" into my SQL statement and I think I'm doing something wrong.. Could someone take a quick look at my query and tell me where I'm missing this operator.
    int insert=stmt.executeUpdate("INSERT INTO tblTest(EnglishName, FileName, RlsID, InitRlsInd, DirID, ObsoleteRlsInd) VALUES
    ("+"\'"+jTextFieldName.getText()+"\'"+","+
    "\'"+jTextFieldFileName.getText()+"\'"+","+
    "\'"+getComboID(jComboBoxRelease)+"\'"+","+
    "\'"+getRadioID(jRadioButtonInitRlsY)+"\'"+","+"OR"+getRadioID (jRadioButtonInitRlsN)+"\'"+","+
    "\'"+getComboID(jComboBoxDirectory)+"\'"+","+
    "\'"+getRadioID(jRadioButtonObsoRlsY)+"\'"+","+"OR"+getRadioID(jRadioButtonObsoRlsN)+"\'"+ ")");
    Thanks in advance.

    cotton if your still out there..
    String sql = "INSERT INTO tblTest("
    + "EnglishName,"
    + "FileName,"
    + "RlsID,"
    + "InitRlsInd,"
    + "DirID,"
    + "ObsoleteRlsInd,"
    + "VALUES(?,?,?,?,?,?)";
    PreparedStatement pstmt = dB.prepareStatement(sql);
    Now if I use pstmt and continue my INSERT I am not able to implement the values the users will put into the text and combo boxes..
    I tried this for the textbox, but it doesn't work... pstmt.setString(jTextFieldName.getText()); I know this is obviously wrong, but I'm unfirmilar with prepared statments and I looked at the Java Docs and they don't show a specific example for what I want to do.. Atleast what I found doesnt. Could you show me a quick example??
    Thanks,

  • Call stored procedure dynamically?

    I wrote a bunch of programs in Perl to output different reports. All these programs are very similar: calling a stored procedure in SQL Server, dump the ResultSet into the file in disk ...
    My boss asked me to write a "Generic" program to combine these programs together so that we don't need write endless similar programs any more.
    I decide to write this program in Java. The new program is supposed to take a stored procedure call as an input parameter (reading from a configuration file, maybe?). It will be great if the program can dynamically determine the field names in the ResultSet from the stored procedure call. In another word, there shouldn't be any hard coded field names in the Java Code. The more generic of the program, the better.
    Is this doable? Does anyone have any such experience before? Any idea or recommendation is highly appreciated.
    Thanks a lot,
    - LX

    Here is some that I wrote:
    //Here is a snippet out of my main program:
                   md = rs.getMetaData();
                   noOfColumns = md.getColumnCount();     
                   //Generate the sql for our prepared statement insert
                   sql = buildInsertSQL("DWXP111", noOfColumns);
                   lowLevel.info("SQL:" + sql);
                   //Create the prepared statment
                   ps = legacyCon.prepareStatement(sql);
                   //Set the prepared statement input parameters
                   while(rs.next())
                        for(int x=1; x<noOfColumns+1; x++)
                             setParameters(x, md.getColumnType(x));     
                        //Execute the prepared statement
                        checkForSuccess(ps.executeUpdate());                    
    //Here is the method it calls:
         private void setParameters(int columnNo, int dataType)
              lowLevel.info("Setting parameter number: " + columnNo);
              lowLevel.info("Data type:" + dataType);
              try
                   switch(dataType)
                        case Types.VARCHAR:
                             ps.setString(columnNo, rs.getString(columnNo)==null ? "" : rs.getString(columnNo).toUpperCase());
                             lowLevel.info("String set:" + rs.getString(columnNo));
                             break;
                        case Types.DECIMAL:
                             ps.setString(columnNo,  rs.getBigDecimal(columnNo)==null ? "0" : rs.getBigDecimal(columnNo).toString());
                             lowLevel.info("Decimal set");
                             break;
                        case Types.CHAR:
                             ps.setString(columnNo,  rs.getBigDecimal(columnNo)==null ? "0" : rs.getBigDecimal(columnNo).toString());
                             lowLevel.info("Char set");
                             break;
              catch (SQLException e)
                   lowLevel.warn("Error while setting parameters for " + dataType + " info");
                   e.printStackTrace();
         }

  • How to activate JDBC debugging for SPRING 3.1? Oracle trigger problems ...

    Hi,
    I have some trigger problems. I created a trigger to update a certain column each time a new record is inserted or an existent record is updated. I use Oracle 10g. If I create the trigger and execute an insert query via the XE client everything works fine. However, when I use a spring 3.1 setup with Hibernate and OJDBC driver, I get an
    java.sql.SQLException: ORA-04098: trigger 'LOCALUSER_PROP_TRIG' is invalid and failed re-validation
    And if I execute a show error trigger query I get an invalid SQL query error.
    I can easily activate Hibernate debugging and I can see that the prepared statement by Hibernate is just fine, but I was wondering if I could see the full sql sent by the JDBC driver to the server. Maybe seeing the actual query sent to the server would provide new insight of what could be wrong in the Hibernate setup. Does any one what could be wrong and eventually how could setup jdbc to output debug info? Thanks a lot,
    Cristian

    Which platform is the database running on ??
    Other things you should check -
    when debugging the EJB, JDev
    3.1 looks through your IIOP connections to find the one to use.
    Make sure that the IIOP connection that JDev is using for the debugging matches the IIOP connection that the EJB client application is using.
    raghu
    null

Maybe you are looking for

  • Stored Procedure for custom permission check

    Hi, I have created 2 UDTs for Master Data and Master Rows, and generated a UDO form for this. Only few users can add master data, but all users should be able to update fields in the rows for existing master records (but not the fields in the header)

  • Can't create ITunes Account

    Just got a new nano & the ITunes Music Store is not allowing me to create an account. I hit "create an account" then move to the "agreement" page. I click on Agree & then my computer tries to start up a windows program & then can't find it so it clos

  • Facing problem in posting to different G/L account

    Hi We are working with Projects system .I have made the PO with account assigment category P and i have different conditions types in calculation schema .Intially the requirement is that all cost is booked to material account be it is freight /excise

  • Customer Exit for Formula Variable

    Hi all, and thanks in advance for your help on this one. I'm trying to run a function module to convert the value of a characteristic in my ODS to a formula variable. To do this, I've created a replacement path variable to hold the value of the chara

  • Zip not compressing?

    I thought the purpose of using a Zip file was to compress files and/or folder for emailing? I've tried multiple times and have successfully made a Zip file of a folder full of jpg photo files. BUT, the Zip file is the same size as the original folder