import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class PgTesti extends HttpServlet { // to use PostgeSQL: final String dbDriver="org.postgresql.Driver"; final String dbServer ="jdbc:postgresql://localhost/laine"; // replace PORTNUMBER/DBNAME with your portnumber and database name // the path to the driver must be in CLASSPATH or the driver copied in .../WEB-INF/lib/ // to use Oracle in bodbacka: final String dbDriver="oracle.jdbc.OracleDriver"; final String dbServer= "jdbc:oracle:thin:@bodbacka.cs.helsinki.fi:1521:test"; // nothing to replace // CLASSPATH must contain /opt/oracle/jdbc/lib/ojdbc14.jar or this must be in .../WEB-INF/lib/ final String dbUser= "puppua"; // replace with your db user account final String dbPassword ="puppua"; // replace with your password public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream out; res.setContentType("text/html"); out= res.getOutputStream(); out.println("PgTesti"); out.println("

PgTesti

"); Connection con=null; con= createDbConnection(dbDriver,dbServer,dbUser,dbPassword,out); if (con==null) { out.println(""); return; } // connection established Statement stmt = null; ResultSet rs = null; try { stmt = con.createStatement(); rs = stmt.executeQuery("select avain, nimi,tieto from testi"); while(rs.next()) { out.println(" avain: "+rs.getInt("avain")); out.println(" nimi: "+rs.getString("nimi")); out.println(" tieto: "+rs.getString("tieto")); out.println("

"); } } catch (SQLException ee) { out.println("Tietokantavirhe "+ee.getMessage()); } finally { try { if (rs!=null) rs.close(); if (stmt!=null) stmt.close(); con.close(); } catch(SQLException e) { out.println("An SQL Exception was thrown."); } } out.println(""); out.println(""); } private Connection createDbConnection( String dbDriver, String dbServer, String dbUser, String dbPassword, ServletOutputStream out) throws IOException { // establish a database connection try{ Class.forName(dbDriver); // load driver } catch (ClassNotFoundException e) { out.println("Couldn't find driver "+dbDriver); return null; } Connection con=null; try { con = DriverManager.getConnection(dbServer,dbUser,dbPassword); } catch (SQLException se) { out.println("Couldn\'t get connection to "+dbServer+ " for "+ dbUser+"
"); out.println(se.getMessage()); } return con; } private void closeConnection(Connection con) { // close database connection try { con.close(); }catch (SQLException e) {} } }