Resultset paging using jsp

I am creating a small search program using jsp. I want to know how can I implement paging using JDBC.
It is very easy using asp. In asp only a specified no. or records can be retrieved from database using combination of PageSize and AbsolutePage properties of Recordset Object.
In jdbc I think there is no such method available. Do I have to use database base specific options to limit the number of records returned like limit keyword in mysql.
Only way I can think of is to create a resultset object and store it in session and then use the absolute() method of the resultset object to go to a specific record and then next(). But still all records have to returned by db and have to be kept in memory and not only specific no. of records (e.g 10 per page).
If I doesn't store the recordset in session then every time this search page is accessed, a new recordset is returned with all records. I then have to determine how many records to skip according to page selected in the query string and then use absolute() method of recordset to go to specific record. And then loop, say ten times to display 10 records. Again when next is clicked same procedure is repeated. Here retrieving all records every time page is accessed is very expensive operation.
In my case even this isn't possible because I am using jdbc odbc bridge, which is not allowing scrollable resultset and jvm is throwing exception in native code. Without scrollable resultset I cannot know how many records are returned. If I try to count using a loop and resultset's next() then I don't have any way to go back to first record again when I actually want to retrieve records to display. Only other way to count the records is executing query twice which isn't very good as records may have been added or deleted between two calls.
Am I wrong anywhere above?
If not then question is, can this be done efficiently with jdbc without using any database specific keywords?
If yes then which method can be used on a busy web site with huge database.
--Sukhwinder Singh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

This may help: http://www.powerobj.com
providing "advice" in this manner is unethical and unhelpful. if you feel a product you are selling would be good for someone you should at the very least disclose your interest in the selling of said product.
the blatant ad you posted in the JavaServer Pages forum at least makes it clear that you are selling a product. this post does not make that clear and it really should be.

Similar Messages

  • Paging in JSP using SQL SERVER 2000

    Hi!!
    How to do paging in JSP using SQL SERVER 2000.
    In my SQL we can fire query like
    ResultSet resultado = declaracao.executeQuery("Select * from tbl_livro limit 20,5 ");
    It means that it fetches 20 onwards 5 records..
    how to do same thing in SQL SERVER 2000 please help it's pretty urgent

    here is the link for paging, what i already post reg this topic
    http://forum.java.sun.com/thread.jspa?threadID=5194183try to avoid multipost next time

  • Paging in JSP using

    Hi!!
    How to do paging in JSP using SQL SERVER 2000.
    In my SQL we can fire query like
    ResultSet resultado = declaracao.executeQuery("Select * from tbl_livro limit 20,5 ");
    It means that it fetches 20 onwards 5 records..
    how to do same thing in SQL SERVER 2000 please help it's pretty urgent

    http://forum.java.sun.com/thread.jspa?threadID=5194183

  • Export to Excel from Database using JSP

    Hi Experts,
    I'm using below jsp code to export from an Oracle table to Excel using JSP.
    Every time I run this code I get the exception - "java.lang.OutOfMemoryError: Java heap space".
    I need to download around 8000+ records of the table containing 60 columns.
    I have increased Heap space but still the exception. Below is the code for your reference (I have mentioned only 30 columns where as there are 60 columns in actual). Pls help me what could be the other possible ways or suggest me any alternate code.
    Pls note - Some of the terms like "<serverip>", MySchema, myfile, COL names are changed for confidentiality.
    "D:\\Myfolder\\Excelfolder\\Final.xls" exists my the local machine.
    The code works until some 4000 records & after that throws the exception.
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@<serverip>:1521:WISTGDEV", "user", "user@123");
    Statement statement = connection.createStatement();
    String filename = "C:\\Myfolder\\Excelfolder\\Final.xls";
    String strQuery1 = ("select * from Myschema.myfile");
    ResultSet rs = statement.executeQuery(strQuery1);
    HSSFWorkbook hwb = new HSSFWorkbook();
    HSSFSheet sheet = hwb.createSheet("sheet1");
    HSSFRow rowhead = sheet.createRow((short)0);
    rowhead.createCell((short) 0).setCellValue("COL1");
    rowhead.createCell((short) 1).setCellValue("COL2");
    rowhead.createCell((short) 2).setCellValue("COL3");
    rowhead.createCell((short) 3).setCellValue("COL4");
    rowhead.createCell((short) 4).setCellValue("COL5");
    rowhead.createCell((short) 5).setCellValue("COL6");
    rowhead.createCell((short) 6).setCellValue("COL7");
    rowhead.createCell((short) 7).setCellValue("COL8");
    rowhead.createCell((short) 8).setCellValue("COL9");
    rowhead.createCell((short) 9).setCellValue("COL10");
    rowhead.createCell((short) 10).setCellValue("COL11");
    rowhead.createCell((short) 11).setCellValue("COL12");
    rowhead.createCell((short) 12).setCellValue("COL13");
    rowhead.createCell((short) 13).setCellValue("COL14");
    rowhead.createCell((short) 14).setCellValue("COL15");
    rowhead.createCell((short) 15).setCellValue("COL16");
    rowhead.createCell((short) 16).setCellValue("COL17");
    rowhead.createCell((short) 17).setCellValue("COL18");
    rowhead.createCell((short) 18).setCellValue("COL19");
    rowhead.createCell((short) 19).setCellValue("COL20");
    rowhead.createCell((short) 20).setCellValue("COL21");
    rowhead.createCell((short) 21).setCellValue("COL22");
    rowhead.createCell((short) 22).setCellValue("COL23");
    rowhead.createCell((short) 23).setCellValue("COL24");
    rowhead.createCell((short) 24).setCellValue("COL25");
    rowhead.createCell((short) 25).setCellValue("COL26");
    rowhead.createCell((short) 26).setCellValue("COL27");
    rowhead.createCell((short) 27).setCellValue("COL28");
    rowhead.createCell((short) 28).setCellValue("COL29");
    rowhead.createCell((short) 29).setCellValue("COL30");
    int index=1
    String name="";
    while(rs.next())
    System.out.println("Inside while");
    HSSFRow row = sheet.createRow((short)index);
    row.createCell((short) 0).setCellValue(rs.getString(2));
    row.createCell((short) 1).setCellValue(rs.getString(3));
    row.createCell((short) 2).setCellValue(rs.getString(4));
    row.createCell((short) 13).setCellValue(rs.getFloat(5));
    row.createCell((short) 4).setCellValue(rs.getString(6));
    row.createCell((short) 5).setCellValue(rs.getString(7));
    row.createCell((short) 6).setCellValue(rs.getInt(8));
    row.createCell((short) 7).setCellValue(rs.getString(9));
    row.createCell((short) 8).setCellValue(rs.getString(10));
    row.createCell((short) 9).setCellValue(rs.getString(11));
    row.createCell((short) 10).setCellValue(rs.getString(12));
    row.createCell((short) 11).setCellValue(rs.getFloat(13));
    row.createCell((short) 12).setCellValue(rs.getFloat(14));
    row.createCell((short) 13).setCellValue(rs.getFloat(15));
    row.createCell((short) 14).setCellValue(rs.getFloat(16));
    row.createCell((short) 15).setCellValue(rs.getFloat(17));
    row.createCell((short) 16).setCellValue(rs.getFloat(18));
    row.createCell((short) 17).setCellValue(rs.getFloat(19));
    row.createCell((short) 18).setCellValue(rs.getFloat(20));
    row.createCell((short) 19).setCellValue(rs.getFloat(21));
    row.createCell((short) 20).setCellValue(rs.getFloat(22));
    row.createCell((short) 21).setCellValue(rs.getString(23));
    row.createCell((short) 22).setCellValue(rs.getString(24));
    row.createCell((short) 23).setCellValue(rs.getString(25));
    row.createCell((short) 24).setCellValue(rs.getString(26));
    row.createCell((short) 25).setCellValue(rs.getString(27));
    row.createCell((short) 26).setCellValue(rs.getString(28));
    row.createCell((short) 27).setCellValue(rs.getString(29));
    row.createCell((short) 28).setCellValue(rs.getString(30));
    index++;
    rs.close();
    FileOutputStream fileOut = new FileOutputStream(filename);
    hwb.write(fileOut);
    fileOut.close();
    connection.close();
    catch(Exception e)
    System.out.println(e.getMessage());
    e.printStackTrace();
    Thanks in advance,
    Venky
    Edited by: Venky_86 on Apr 15, 2009 12:06 AM

    Its is an obvious thing...POI is known to need a lot of memory (the reason for that is most likely the OLE document format, which is quite complex).
    I would have used something like the below to see if that can address my client's requirement.
    public exportExcel(String fileName){
       Connection connection = null;
       Statement statement = null;
       ResultSet rs = null;
       PrintWriter out = null;
       int index=1;
       try{
         out = new PrintWrite(new FileWriter(fileName));
         connection = DbUtils.getConnection();
         statement = connection.createStatement();
         rs = statement.executeQuery("select * from Myschema.myfile");
         out.prinln("<table>");
         out.println("<th>COL1</th>");
         out.println("<th>COL2</th>");
         out.println("<th>COL3</th>");
         out.println("<th>COL4</th>");
         out.println("<th>COL5</th>");
         out.println("<th>COL6</th>");
         out.println("<th>COL7</th>");
         out.println("<th>COL8</th>");
         out.println("<th>COL9</th>");
        out.println("<th>COL30</th>");
         out.println("<thead>");
         out.println("<tbody>");
         while(rs.next()){
              out.println("<td>"+index+"</td>");
              out.println("<td>"+rs.getString(2)+"<td>");        
              out.println("<td>"+rs.getString(3)+"<td>");        
              out.println("<td>"+rs.getString(4)+"<td>");        
              out.println("<td>"+rs.getString(5)+"<td>");        
              out.println("<td>"+rs.getString(6)+"<td>");        
              out.println("<td>"+rs.getString(7)+"<td>");        
              out.println("<td>"+rs.getString(8)+"<td>");        
              out.println("<td>"+rs.getString(9)+"<td>");        
              out.println("<td>"+rs.getString(30)+"<td>");        
         out.println("</tbody>")     
         out.println("</table>");    
         out.flush(); 
       }catch(Exception exp){
           exp.printStackTrace();
       }finally{
           if(out != null)
            try{out.close();}catch(Exception e){}
             if(rs != null)
               try{rs.close();}catch(Exception e){}
            if(statement != null)
               try{statement.close();}catch(Exception e){}
             if(connection != null)
               try{connection.close();}catch(Exception e){}
    }and you can simply export the file using the method
    ApplicationUtils.getInstance().exportExcel("c:/export/myapp/ApplicationTable.xls");If you are using Office 2000 and above you should able open it as an excel worksheet without any problems.
    Hope that help :)
    REGARDS,
    RaHuL

  • Diaplay  Word file stored in blob into a browser using JSP

    Dear All
    I have files stored in oracle table in a blob field.I store the files using forms 10g and webutil. I can upload the files and display them successfully in forms, however when i use JSP to retrieve the files and display them in Internet Explorer, I'm able to display the pdf files, bmp , jpg and video but I'm getting junk characters when I try displaying (word , excel , access or powerpoint files which might contain arabic Characters )
    the code I use to display the files is as follows :
    <%
    try
    Connection conn = null;
    String username=session.getAttribute("username").toString().toUpperCase();
    String password=session.getAttribute("password").toString().toUpperCase();
    String ip = "*****************";
    String sid = "***************";
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn = DriverManager.getConnection("jdbc:oracle:thin:@"+ip+":1521:"+sid,username,password);
    String par = request.getParameter("LETTER");
    String par1 = request.getParameter("SERIAL");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select * from TableName where PK1 like '"+par+"'"+" and PK2 like '"+par1+"'" );
    if (rs.next())
    Blob pic = null;
    byte[] blobBytesArray = null;
    OutputStream stream = response.getOutputStream();
    pic = rs.getBlob("BLOBFIELD");
    int len = new Integer( new Long( pic.length()).toString() ).intValue();
    blobBytesArray = pic.getBytes(1,len);
    if (blobBytesArray != null)
    if (blobBytesArray.length > 0 )
    stream.write(blobBytesArray) ;
    catch(Exception e)
    System.out.println("Exception: " + e.getMessage() + "<BR>");
    %>
    can you please guide me of how to display other file types.
    Best Regards.

    Hello,
    Ideally when you store the document put the content-type in a column and set the content type in your JSP. This will indicate to the browser what is the type of file and you should not have any issue with any type.
    Regards
    Tugdual Grall

  • Retrieve image from my sql database using jsp

    I want to retrieve image from my sql (blob type) & save it in given relative path in server .(using jsp and servlets)
    please give me some sample codes.

    PreparedStatement pst = null;
      ResultSet rs=null;
    pst = conn.prepareStatement("select image from imagedetails where imageid='"+imageid+"'");
    rs=pst.executeQuery();
    while(rs.next())
                                byte[] b=rs.getBytes("image");
                                FileOutputStream fos=new FileOutputStream("c://image.jpg");
                                fos.write(b);
                            } hi this the code to retrieve the image from DB and write to a file.

  • How to display my ResultSet in a JSP??

    First off, I'm new to Java programming.
    Here's my problem. I have a set of users in my database. I'd like to retrieve all the user ID's (these are integers) from my User-table and display them in a JSP. Now, I realize that my coding below isn't very efficient as it's not exactly a MVC approach. I'm just trying to learn what a ResultSet is and how to manipulate it.
    I send my ResultSet to a JSP by "request.setAttribute("usersId", usersId);" but then I'm not sure what to do in my JSP to actually display my User ID's.
    My code:
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try {
    String dbURL = "jdbc:mysql://localhost:3306/heading360";
    String username = "root";
    String password = "";
    Connection connection = (Connection) DriverManager.getConnection(
    dbURL, username, password);
    Statement statement = (Statement) connection.createStatement();
    ResultSet userId = (ResultSet) statement.executeQuery("SELECT UserId FROM User");
    request.setAttribute("userId", userId);
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/testUserId.jsp");
    dispatcher.forward(request, response);
    catch (SQLException e) {
    for (Throwable t : e)
    t.printStackTrace();
    }

    flukyspore wrote:
    OK thanks for the quick response.
    I am using using JSP EL to write my JSP's. Still learning JSTL.Bad idea. Learn JSTL.
    I understand everything you're saying, except I can't seem to find the exact approach to load my ResultSet into an object or collection. Could you give me an example of how to do that. My ResultSet is one column of User ID's, they are integers. Something like this:
    private static final String FIND_USER_ID_SQL = "SELECT USER_ID FROM USERS";
    private Connection connection;
    public List<Integer> findUserIds()
        List<Integet> userIds = new ArrayList<Integer>();
        Statement stmt = null;
        ResultSet rs = null;
        try
            stmt = connection.createStatement(sql);
            rs = stmt.executeQuery();
            while (rs.next())
                userIds.add(rs.getInt("USER_ID"));
        catch (SQLException e)
            e.printStackTrace();
        finally
            close(rs);
            close(stmt);
        return userIds;
    }Fill in the blanks.
    %

  • Problem with database using JSP

    Hi
    i am developing one application which uses JSP ..to connect to the database..at present i am using MS-access for the data storage...
    I have two pages in one page there is a form where user fills all the details and once submit the information based on the form has to fetch the data from the backend...i have a problem ..if i hard code the corresponding column name in the JSP page it is getting all the data but if i get it from request.getParameter("")( which i am supposed to be from the form) i am getting no records..
    take a look at the code below and let me know...
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    java.sql.Connection conn= java.sql.DriverManager.getConnection("jdbc:odbc:asiafinity");
    java.sql.Statement stmt=conn.createStatement();
    /* If i print a value from the previous pages its showing but its not going to the database with query statement..
    // String str1=request.getParameter("religion");
    // System.out.println(str1);
    /* If i hardcode the corresponding columun data its querrying the data
    String str1="hindu";
    String sqlquery="select * from userprofile where religion='"+str1+"'";
    System.out.println(str1);
    java.sql.ResultSet cols=stmt.executeQuery(sqlquery);
         while(cols.next()){
    String gen=cols.getString("gender");
    String age=cols.getString("age");
    String rel=cols.getString("religion");
    String cul=cols.getString("culture");
    String loc=cols.getString("location");
    String pro=cols.getString("profession");
    String uname=cols.getString("username"); %>
    <tr><td><a href="<%=uname%>"><%=uname%></td>
    <td><%= gen %></td>
    <td><%= age %> </td>
    <td><%= rel %> </td>
    <td><%= cul %> </td>
    <td><%= loc %></td>
    <td><%= pro %></td>
    </tr>
              <% } %>
    Please help me out..i know this is an simple problem
    Thanks & Regards
    Gnanesh
    </a>

    String str1=request.getParameter("religion");
    String sqlquery="select * from userprofile where religion='"+str1+"'";
    System.out.println(sqlquery);
    try it and tell me what happens

  • How to make  paging in JSP?

    I would like to know how to make paging in JSP?
    PLEASE HELP ME !

    It is much easier , if you use MVC framework, you can store
    results in session appropriate action to servlet, it will serve page by page.

  • Best Practive to resturn Resultset to a JSP page

    I'm writing a class to return a resultSet to use in a JSP page or at least i think thats what i want to do. Whats the best practice to return that resultset.....As the class is written below, when i try to iterate through the resultset in the jsp page i get a NullPointerException which i understand because i closed the connection before returning....If i take out all the code in the finally section i can iterate through the data no problem....but thats not good to leave connections open.......instead of returning a resultset should i return some other type such as an Array with all the data. How should i return the data?
    ======================================================================
    package foo;
    import javax.naming.*;
    import javax.sql.*;
    import java.sql.*;
    public class DBTest{
    String foo = "Not Connected";
    String bar = "Not";
    public ResultSet getUser(){
    Connection conn = null;
    Statement stmt = null; //Or preparedStatement if needed
    ResultSet rs = null;
    try{
    Context ctx = new InitialContext();
    if(ctx == null)
    throw new Exception("Boom - No Context");
    DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/Show");
    if(ds != null){
    conn = ds.getConnection();
    if(conn != null){
    foo = "Got Connection " + conn.toString();
    stmt = conn.createStatement();
    rs = stmt.executeQuery("SELECT * FROM user");
    if(rs.next()){
    foo=rs.getString("login");
    bar=rs.getString("password");
    }catch(Exception e){
    e.printStackTrace();
    }finally{
    // Always make sure result sets and statements are closed,
    // and the connection is returned to the pool.
    if(rs != null){
    try{
    rs.close();
    }catch(SQLException e){;}
    rs=null;
    if(stmt != null){
    try{stmt.close();}catch(SQLException e){;}
    stmt=null;
    if(conn != null){
    try{conn.close();}catch(SQLException e){;}
    conn=null;
    return rs;
    public String getFoo(){return foo;}
    public String getBar(){return bar;}

    Yes, when you close your connection all data in your result set is lost, and yes its not a good idea to keep connections open. Its also not a good idea to pass results around. What you should do is store the data in some type of collection object and pass that to your jsp.
    for exmaple if you select data from a table that stores names of people, e.g. two columns first_name and last_name, then create a class called People with two private string members to hold the first and last names. loop through your result set and build a People object for each row of data. when your done close the result set (and the connection if you want). store all your People objects is a collection (vector, array, whatever). pass the vector to your jsp for display.
    -S-

  • How to create Reports and Forms using JSP

    Hi,
    How to create reports using JSP. And how many types of reports can be created using JSP.Can anyone explain with example please.
    Thanks,
    Vijayalakshmi.M

    Here is some code that creates xml for any SQL that returns a ResultSet. Note this uses my default out-of-the-box XML template, but you can quickly create and use your own templates to generate xml to look anyway you desire.
    FormattedDataSet fds=FormattedDataSet.createInstance();
    Map miscData=new HashMap();
    map.put("rootElement", "musicgroups");
    String xml=fds.getFormattedDataSet("select * from groups", miscData, "xml1");
    String xml has the value:
    <musicgroups>
    <row rowID='1'>
      <group_id>1</group_id>
      <group_name>Rolling Stones</group_name>
      <type>Rock</type>
    </row>
    <row rowID='2'>
      <group_id>2</group_id>
      <group_name>Beatles</group_name>
      <type>Rock</type>
    </row>
    <row rowID='3'>
      <group_id>3</group_id>
      <group_name>Led Zepplin</group_name>
      <type>Rock</type>
    </row>
    </musicgroups>steve -
    http://www.fdsapi.com - The easiest way to generate dynamic HTML and XML
    http://www.jamonapi.com - A performance tuning and scalability measuring API

  • Paging in JSP(Scriptlets) help-me! help-me! help-me!

    Somebody can order an example of paging in JSP. does not obtain to make the paging.... Please, somebody can help.....� an urgency case me! In case that somebody has some example please, [email protected] orders pro email If possivel in Scriptlets
    Very Obliged!

    <%@ page import="java.sql.*" %>
    <%@ page errorPage="err.jsp" %>
    <%
    By VendeW and Shibayama
    %>
    <html>
    <body>
    <center>
    <h2>Pagina��o usando JSP e MySQL</h2>
    <table border="2">
    <tr bgcolor="tan">
    <th>id</th><th>Titulo</th><th>Image</th><th>Descri��o</th></tr>
    <%
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
    Connection conexao = DriverManager.getConnection("jdbc:odbc:book");
    Statement declaracao = conexao.createStatement();
    Statement declaracao2 = conexao.createStatement();
    int limitePorPagina = 5;
    ResultSet resultado = declaracao.executeQuery("Select * from tbl_livro limit " + request.getParameter("pr") + "," + String.valueOf(limitePorPagina));
    ResultSet rs2 = declaracao2.executeQuery("Select count(*) as c from tbl_livro");
    rs2.next();
    int totalregs = Integer.parseInt(rs2.getString("c"));
    %>
    <b>Total de Registros: </b><%=totalregs%>
    <%
    int totalpgs = Math.round(totalregs / limitePorPagina);
    out.write("<b>P�ginas:</b> " + totalpgs);
    if ((totalregs % limitePorPagina) > 0) totalpgs++;
    int pr = Integer.parseInt(request.getParameter("pr"));
    try {
    while (resultado.next()) {
    String id = resultado.getString("id_livro");
    String nm = resultado.getString("nm_livro");
    String img = resultado.getString("image");
    String desc = resultado.getString("desc_livro");
    %>
    <tr>
    <td><%=id%> </td>
    <td><%=nm%> </td>
    <td><%=img%> </td>
    <td><%=desc%> </td>
    </tr>
    <%
    }//while (resultado.next())
    %>
    </table>
    <%
    }//try
    catch (SQLException e) { out.println("SQL Error" + e); }
    if (pr > 0) {
    %>
    [Primeira P�gina] 
    <a href="?pr=<%=pr-limitePorPagina%>">[Anteriores]</a> 
    <%
    }//if (pr > 0)
    if (pr < (totalpgs * limitePorPagina) - limitePorPagina) {
    %>
    <a href="?pr=<%=pr+limitePorPagina%>">[Pr�ximos]</a> 
    <a href="?pr=<%=(totalpgs * limitePorPagina) - limitePorPagina%>">[Ultima P�gina]</a> 
    <%
    }//if (cont < totalpgs)
    %>
    </center>
    </body>
    </html>

  • Using JSP to connect to an Access Database

    I need help on using JSP to connect to an Access database.
    This is the code I currently have connecting to a mySQL DB. I need to change it to connect to an Access DB. The reason I am switching DB's is because mySQL is no longer going to be carried by my host.
    Here is the code:
    <html>
    <head>
    <basefont face="Arial">
    </head>
    <body>
    <%@ page language="java" import="java.sql.*" %>
    <%!
    // define variables
    String UId;
    String FName;
    String LName;
    // define database parameters
    String host="localhost";
    String user="us867";
    String pass="jsf84d";
    String db="db876";
    String conn;
    %>
    <table border="2" cellspacing="2" cellpadding="5">
    <tr>
    <td><b>Owner</b></td>
    <td><b>First name</b></td>
    <td><b>Last name</b></td>
    </tr>
    <%
    Class.forName("org.gjt.mm.mysql.Driver");
    // create connection string
    conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user + "&password=" +
    pass;
    // pass database parameters to JDBC driver
    Connection Conn = DriverManager.getConnection(conn);
    // query statement
    Statement SQLStatement = Conn.createStatement();
    // generate query
    String Query = "SELECT uid, fname, lname FROM abook";
    // get result
    ResultSet SQLResult = SQLStatement.executeQuery(Query);
         while(SQLResult.next())
              UId = SQLResult.getString("uid");
              FName = SQLResult.getString("fname");
              LName = SQLResult.getString("lname");
              out.println("<tr><td>" + UId + "</td><td>" + FName + "</td><td>" + LName
    + "</td></tr>");
    // close connection
    SQLResult.close();
    SQLStatement.close();
    Conn.close();
    %>
    </table>
    </body>
    </html>
    Thank You,
    Josh

    <%@ page language="java"%>
    <html>
    <head>
    <title>
    First Bean
    </title>
    <%@ page import="java.sql.*" %>
    </head>
    <body>
    <p>
    <%!
    Connection con;
    Statement st;
    ResultSet rs;
    String userid;
    String password;
    %>
    <%!public void db(JspWriter out)
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:phani");
    catch(Exception e){}
    try{
    st=con.createStatement();
    rs=st.executeQuery("SELECT * FROM login");
    while(rs.next())
    userid=rs.getString("userid");
    password=rs.getString("password");
    out.println(userid);
    out.println("</br>");
    out.println(password);
         out.println("</br>");     
    }catch(Exception e){}
    try{
    con.close();
    }catch(Exception e){}
    %>
    <%db(out);%>
    </p>
    </body>
    </html>
    phani is dsn name
    login is table name
    Good luck
    phani

  • Dynamic combobox using jsp

    HI All,
    This is very urgent for me please help me to come out of this.
    I just want to display the values in combobox from database using jsp,but i have difficulty in doing it can any one help me for this.I will be thankfull if any one gives me a code for the same.
    Ramesh.R

    very simple example
    <%@ page import="java.sql.*" %>
    Add Item:
    <SELECT NAME="item">
    <ol>
    <%
    Connection con5 =
    DriverManager.getConnection("url","user","password");
    String q5 = "query" ;
    Statement stmt5 = (Statement)con5.createStatement();
    ResultSet rs5 = stmt5.executeQuery(q5);
    while(rs5.next()){
    String str5= rs5.getString("field");
    %>
    <li> <% out.print("<OPTION>" + str5); %>
    <% } %>
    </ol>
    </SELECT>

  • Error in File uploading using jsp

    I am tring to upload files to a mysql database using jsp.I have used BLOB type to store files.Iam using the JDBC driver mysql-connector-java-2.0-14-bin to connect the database with the jsp API.My problem is when i try to transfer a file of size which is less than the possible capacity through blob ,which is 1048576 bytes ( for example when a file of size 916KB is attempted to transfer) the following error is being generated.
    java.lang.IllegalArgumentException: Packet is larger than max_allowed_packet from server configuration of 1048576 bytes
         at com.mysql.jdbc.Buffer.ensureCapacity(Unknown Source)
         at com.mysql.jdbc.Buffer.writeBytesNoNull(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at org.apache.jsp.file3$jsp._jspService(file3$jsp.java:110)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:201)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:381)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:473)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:190)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2347)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:468)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor.java:1027)
         at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.java:1125)
         at java.lang.Thread.run(Thread.java:484)
    java.lang.IllegalArgumentException: Packet is larger than max_allowed_packet from server configuration of 1048576 bytes
         at com.mysql.jdbc.Buffer.ensureCapacity(Unknown Source)
         at com.mysql.jdbc.Buffer.writeBytesNoNull(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at org.apache.jsp.file3$jsp._jspService(file3$jsp.java:110)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:201)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:381)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:473)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:190)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2347)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:468)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor.java:1027)
         at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.java:1125)
         at java.lang.Thread.run(Thread.java:484)
    My uploading code in jsp is as follows.
         <% try{
              Class.forName("org.gjt.mm.mysql.Driver").newInstance();
              Connection dbCon = DriverManager.getConnection("jdbc:mysql:///uoc");
              out.println("Connection done !");
              Statement stmt = dbCon.createStatement();
              out.println("Statement Created !");
    ResultSet rs = stmt.executeQuery("SELECT * FROM blob_test)
    stmt.close();
    dbCon.close();
    out.println("<br><br> <b>Data Successfully selected !<b>");
    } //try
    catch(SQLException e){
         out.println(" <br> ");
         out.println("Sorry ! problem in selecting a data "+e.toString());
         out.println(" <br> ");
                   e.printStackTrace();
    %>
    Please help .I thank You in advance for any help .

    Have you tried increasing the BLOB field greater than 1048576 or using a smaller file of say 1 or 2k as a test? There is no guarantee that the database will store the file with exactly the same size as the file on the filesystem, so the file might be more than 916k in the database.
    Using BLOBs is a great way to destroy the performance of your database by the way :)

Maybe you are looking for