Thread: servlet problem

servlet problem

From
Ralf Weidemann
Date:
Hi all,

I did a stress test with apache bench (ab -n 1000 -c 10
http://onyx:8080/devserv/test2) on the below code (based
on 'basic.java' from the jdbc interface examples). Well
and while ab was running I also called the servlet from
netscape and got sometimes not the whole output. What's
wrong here ? Have I here a transaction problem ? Or some
other connection problems ? I tried first the whole
basic.java sample and the database got damaged and I
could not create any new tables. Well, here I think I
must do some transaction handling, right ? But the below
code does only some SELECTs ? Need I always some trans-
action handling ? I was thinking it's only needed for
writing.

Thanks,
Ralf


public class test2 extends HttpServlet {
    PrintWriter out;
    Connection db;    // The connection to the database
    Statement  st;    // Our statement to run queries with
    String url = "jdbc:postgresql://onyx/test";
    String usr = "test";
    String pwd = "test";

    public void doGet (HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException
    {
        try {
            response.setContentType("text/plain");
            out = response.getWriter();
            out.println("START");
            Class.forName("postgresql.Driver");
            out.println("Connecting to Database URL = " + url);
            db = DriverManager.getConnection(url, usr, pwd);
            out.println("Connected...Now creating a statement");
            st = db.createStatement();
            out.println("\nRunning tests:");
            out.println("Performing a query");
            ResultSet rs = st.executeQuery("select a, b from basic");
            if(rs!=null) {
                while(rs.next()) {
                    int a = rs.getInt("a");
                    int b = rs.getInt(2);
                    System.out.println("  a="+a+" b="+b);
                }
                rs.close();
            }
            out.println("performing another query");
            rs = st.executeQuery("select * from basic where b>1");
            if(rs!=null) {
                int col_a = rs.findColumn("a");
                int col_b = rs.findColumn("b");

                while(rs.next()) {
                    int a = rs.getInt(col_a);
                    int b = rs.getInt(col_b);
                    out.println("  a="+a+" b="+b);
                }
                rs.close();
            }
            out.println("Now closing the connection");
            st.close();
            db.close();
            out.println("END");
            out.close();
        } catch(Exception ex) {
            // We ignore any errors here
        }
    }
}