Open and close database connection jsp page

hi there, i wanna know about how to open database connection to Mysql at the beginning of the page and close the connection at the end of the page. The jsp page contain all processing code.
plz help me...thx thx

<html>
<head>
<basefont face="Arial">
</head>
<body>
<%@ page language="java" import="java.sql.*" %>
<%!
// define variables
String id;
String firstName;
String lastName;
// define database parameters, change this according to your needs
String host="localhost";
String user="root";
String pass="";
String db="test";
String conn;
%>
<table border="1" cellspacing="1" cellpadding="5">
<tr>
<td><b>id</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
// change this query according to your needs
String Query = "SELECT id, firstname, lastname FROM abook";
// get result
ResultSet SQLResult = SQLStatement.executeQuery(Query);
while(SQLResult.next())
   id = SQLResult.getString("id");
   firstName = SQLResult.getString("firstname");
   lastName = SQLResult.getString("lastname");
        out.println("<tr><td>" + id + "</td><td>" + 
     firstName + "</td><td>" + lastName + "</td></tr>");
// close connection
SQLResult.close();
SQLStatement.close();
Conn.close();
%>
</table>
</body>
</html>hi :-)
i've got that on the net as part of the tutorial on jsp (long long time ago)
you just have to be resourceful in finding solutions :-)
try google :-) there are lot's of tutorial available in there ;-)
goodluck ;-)
regards,

Similar Messages

  • When to open and close database connection

    im trying to connect to a oracle database using servlets
    when should i open and close the connection
    it works fine when i do both in the doPost() method
    but when i tried to open connection in init() methd .. it doesnt seem to work
    what should i do...
    the connection is initialised in the init() method but is null in the doPost() method

    " im trying to connect to a oracle database using servlets
    when should i open and close the connection
    it works fine when i do both in the doPost() method
    but when i tried to open connection in init() methd .. it doesnt seem to work
    what should i do...
    the connection is initialised in the init() method but is null in the doPost() method"
    1:
    without seeing the code i would say the the connection is null
    because you are storing it as a servlet class variable which is
    not thread safe.
    2:
    The best way to do it using connection pooling
    detailed docs on the tomcat website
    3:
    if you are not using connection pooling, then
    open and close the connection in the do* method
    or
    use init() to place the connection in the servletconfig
    and close in destroy() and use synching to access

  • Open and close RFC connection with portals...

    Hi Experts,
    I created a RFC having a query which is taking a long time to execute. So i want to close RFC connection with portals which is via java connector(JCO)  before that query and open the connction again after that query.
    Please advice is it possible to achieve this. If yes, then how.
    Regards,
    Guddan

    Hi Guddan,
    I created a RFC having a query which is taking a long time to execute. So i want to close RFC connection with portals which is via java connector(JCO) before that query and open the connction again after that query.
    I guess i will need to understand your requirement a little more in detail, as i understand you have an RFC which has a query within to fetch some data and is taking a long time to do so. In the meantime you don't want to keep the connection open?
    My question would be, Is the role of this RFC to only execute the query and fetch the data or does it do something else?
    If it does other things and these are independent of the query execution, then you can span a parallel call within the RFC to execute the query and in the meantime the RFC does the other things (or vice versa) hence reducing the overall time taken.
    If the sole purpose of this RFC is to execute the query, then you will not be able(i mean to say there is no simple and direct way of doing this) to close the connection after the Query is started and re-establish the connection after its execution, for a simple reason that - how will you know if the query has completed it's execution, so that you can establish the connection back.
    Alternate solutions, make this a two way asynchronous call, 1) You invoke the RFC asynchronously and close the connection, the RFC in turn will execute the query and transfer the data to JCO via another RFC call.
    If this needs to be a synchronous call, then you will need to optimize the query to its best.
    Regards,
    Chen

  • Opening and closing database from JSPs

    Hi,
    I have a few web pages with an underlying database, and after some research I seem to have found that accessing this database directly from the JSP is a bad idea. Because of this I have created 2 methods in my JavaBean class to create the database connection and to close the database connection. What I want to have happen is when the user logs in the the site, a database connection is opened by calling the databaseConnection method then once they close the browser the destroyDBConnection is called. How do I go about implementing this approach in my JSPs? thanks for any suggestions
        * Method to create database connection
        public static void dbConnection() {
          try{
              // Step 1: Load the JDBC driver.
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                // Step 2: Establish the connection to the database.
                String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
                        "DBQ=C:\\Program Files\\Apache Software Foundation\\Tomcat 5.5" +
                        "\\webapps\\TheatreDepartment.mdb";
                connection = DriverManager.getConnection(url);
              connection.setAutoCommit(false);
          } catch (SQLException se) {
              System.out.println("SQL Error while connecting to the database : "+
                                  se.toString());
          } /*catch (NamingException ne) {
              System.out.println("Naming exception Error while connecting to the database : "+
                                  ne.toString());
          } */catch (Exception ne) {
              System.out.println("Error while connecting to the database : "+
                                  ne.toString());
        * Destroy the Connection Object.
        public static void destroyDbConnection() throws SQLException {
              if (connection != null || !connection.isClosed() ) {
                connection.close(); // close the connection
      }

    I would suggest you do some more research.
    Take a look into connection pooling.
    Most of the time you do NOT want to give each individual user their own database connection, but rather keep a bunch on hand for people to use.
    http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-resources-howto.html
    http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html

  • What is the better way to open and close connection in bean

    Hello, may i ask about the best way to open and close the connection?
    At the first, the connection code is store in Conn class bean. The JSP page will call a method in Process bean to process the query and update of database. the Process bean is using th Conn to connect to database.
    In my process bean, it have a method for each type of sql like select, insert, update, and delete for each tables. Each method will call the Conn to open and close the connection. The jsp page can simply call a method retrieve or update records.
    However, when calling the processUpdate method, it is a method that update a group of tables base on the query result of another group of tables and calculation. If I calling the query method in the same bean file, it will open and close the connection many times (more than 1000 times). After open and close the connection several times, the connection to mySQL will be fail.
    Currently, i include 2 method in Process that is only calling the Conn to open the connection and close connection. When calling the openConnection method, it will also set the boolean connected in the class to true and call Conn to open connection. When calling the closeConnection method, it will also set the boolean connected in the class to false and call Conn to close connection.
    After that, i add some change to the query method which is when the connected is false, it will open the connection by calling the Conn and close the connection themself. If the connected is true, it will not call the Conn to open and close the connection because it already connected to the database.
    Now, i when i calling the query method in jsp, it can open the connection and close the connection individually. When i call the processUpdate in the jsp, this method will calling the openConnection before calling the query and calling closeConnection at the end. It not only faster the process(less open and close), it also no cause the connect to mySQL fail error again. However, it also make the coding in the bean file more longer and complex.
    Is there have any better solution?

    Use connection pooling. This will put the connection management in the hands of the webserver, not your code. Check out this post:
    http://forum.java.sun.com/thread.jspa?threadID=741788&messageID=4252932#4252932

  • When and How to close database connection in JSP?

    Hi there,
    I am using MySQL and JDBC 3.0, in my system, When and How to close database connection in JSP?
    Thanks in advance.
    Lonely Wolf
    <%@ page session="true" language="java" %>
    <jsp:include page="checkauthorization.jsp" />
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
    <%--
    Execute query, with wildcard characters added to the
    parameter values used in the search criteria
    --%>
    <sql:query var="availablecomputerList" dataSource="jdbc/Bookingcomputer" scope="request">
    SELECT * FROM computer where status=0
    order by s_code
    </sql:query>
    <html>
    <head>
    <title>Search Result</title>
    </head>
    <body bgcolor="white">
    <center>
    <form action="checkin.jsp" method="post">
    <input type="submit" value="Back to Check-in Page">
    </form>
    <c:choose>
    <c:when test="${availablecomputerList.rowCount == 0}">
    Sorry, no available computer found.
    </c:when>
    <c:otherwise>
    The following available computers were found:
    <table border="1">
    <th>Computer</th>
    <th>Description</th>
    <th>Status</th>
    <c:forEach items="${availablecomputerList.rows}" var="row">
    <tr>
    <td><c:out value="${row.s_code}" /></td>
    <td><c:out value="${row.description}" /></td>
    <td><c:out value="${row.status}" /></td>
    </tr>
    </c:forEach>
    </table>
    </c:otherwise>
    </c:choose>
    </center>
    </body>
    </html>

    when should you close the connection? when you're done with it.
    how should you close the connection? like this: conn.close();
    that said, doing this in a JSP page is bad form and not recommended
    JSP's typically don't contain ANY business or data logic

  • Pages 09 document; open and close many times; right way with Lion?

    I have a 106 page document that increases in size on a daily basis. With OS 10.7, iWork/Pages 09 on my new, iMac, it's common that I lose as much as two sentences after the document is closed and re opened. After 10.7 was installed the document was closed using Command - S, and subsequently closed by pulling down File and selecting Close. - Not the way to close; the red button was so easy with 10.6. IS UNINSTALLING LION THE BEST SOLUTION?
    And yes, I've read the sorry jibberish in the Pages 09 manual - which doesn't say how to open and close repeatedly a document with Pages 09.
    So, with the Lion - the worst ever of spending $30, is it necessary to do a Command S every time you close? And what exactly is necessary each time you close a document using Pages 09 and Lion? - And about Auto Save; well, what about Auto Save? - The Lion means well for something other than common, understandable, text production.  -- How about a separate application of Appleworks for text producers like me?

    The red button is always available under 10.7 (or 10.7.1)
    Under 10.7, press cmd + S once when you create the document.
    After that, the system automatically save your changes.
    No need for cmd + S.
    To close the document we may use :
    the red button
    cmd + W
    File > Close
    as it was with older systems.
    monte45 wrote:
    And yes, I've read the sorry jibberish in the Pages 09 manual - which doesn't say how to open and close repeatedly a document with Pages 09.
    The User Guide is perfectly clear and precise :
    Yvan KOENIG (VALLAURIS, France) jeudi 22 septembre 2011 19:21:52
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.0
    My iDisk is : <http://public.me.com/koenigyvan>
    Please : Search for questions similar to your own before submitting them to the community

  • IPad mini randomly opens and closes apps, changes pages on book readers

    My iPad mini has gone crazy, it randomly opens and closes apps, plays games itself, changes pages whilst reading a book, starts flashing. Tried everything, rebooted the device, updated it always with the latest software update and have reset the iPad as a new IPad with no success. The problem still occurs which is really enjoying. I checked on the Internet and I'm not the only one with an iPad mini with this problem. The iPad is older than one year, what are my chances of resolving this and how?

    I have this problem with my PDFs too. I'm using a lot of PDFs from the German RPG "The Dark Eye" (Das schwarze Auge) from their the PDF shop "ulisses ebooks".
    However, i recognized that I don't get this random black boxes after a restart of the iPad Air for a long time. But when it starts it's become very frequently.
    To remove the black boxes for a single page i can close the book and reopen it or just mark text from the corrupted page. Zoom in removes the black boxes too, but if you zoom out there are visible again.
    I also recognzied that this must be a problem if the iPads PDF engine and not from iBooks. I got the same random black boxes in a PDF which I viewd in Safari.
    I think that changing the reader will only help if it has its own PDF Engine. Don't know if this possible in iOS.
    Perhaps it's some kind of memory leak of the iOS PDF Engine, after this bug apperas only after some time of ussage.

  • Problem in Retrieve Image from DB and display in the JSP page

    Hi All,
    I did one JSP Program for retriveing image from DB and display in the JSP Page. But when i run this i m getting "String Value" output. Here i have given my Program and the output. Please any one help to this issue.
    Database Used : MS Access
    DSN Name : image
    Table Name: image
    Image Format: bmp
    Output : 1973956
    Sample Program:_
    <%@ page contentType="text/html;charset=windows-1252"%>
    <%@ page import="java.io.*" %>
    <%
         try{
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              Connection conn = DriverManager.getConnection("jdbc:odbc:image");
              Statement st = conn.createStatement();
              ResultSet rs = st.executeQuery("SELECT images FROM image");
              String imgLen="";
              if(rs.next()){
                   imgLen = rs.getString(1);
                   out.println(imgLen.length());
              if(rs.next()){
                   int len = imgLen.length();
                   byte [] rb = new byte[len];
                   InputStream readImg = rs.getBinaryStream(1);
                   int index=readImg.read(rb, 0, len);
                   System.out.println("index"+index);
                   st.close();
                   response.reset();
                   response.setContentType("image/jpg");
                   response.getOutputStream().write(rb,0,len);
                   response.getOutputStream().flush();
         }catch(Exception ee){
              out.println(ee);
    %>
    Thanks,
    Senthilkumar S

    vishruta wrote:
    <%
    %>Using scriptlets is asking for trouble. Java code belongs in Java classes. Use a Servlet.
                   out.println(imgLen.length());Your JSP was supposed to write an image to the output and you wrote some irrelevant strings to the output before? This will corrupt the image. It's like opening the image in a text editor and adding some characters before to it.
                   byte [] rb = new byte[len];Memory hogging. Don't do that.
              out.println(ee);You should be throwing exceptions and at least printing its trace, not sending its toString() to the output.
    You may find this article useful to get an idea how this kind of stuff ought to work: [http://balusc.blogspot.com/2007/04/imageservlet.html].

  • Apps open and close alone...

    Hi,
    I have the Ipad 3 with IOS 6 and yesterday, suddenly, the apps and everything started working without touching the screen. Everything opens and closes immediately without stopping. I barely could turn it off. I finally reset it but still the same. I restore it completly with iTunes but still the same. Has enyone experienced this?? Can't use it!
    Thanks

    Any Accessibility features activated in iTunes?
    page 107, iPad_user_guide
    You can turn individual accessibility features on or off in Accessibility settings on iPad. You can also turn some features on or off in iTunes when you connect iPad to your computer.
    Turn on accessibility features using iPad: Go to Settings > General > Accessibility.
    Turn on accessibility features using iTunes: Connect iPad to your computer and select iPad in the iTunes device list. Click Summary, then click Configure Universal Access at the bottom of the Summary screen.

  • Can not open safari. When I launch safari it opens and closes very quickly

    I have an internet connection but I can not open safari, my apps that require internet connection still work. When I launch safari it opens and closes very quickly. I have tried rebooting the Ipad several times, and have already cleared the history, cache and cookies. Please Help!!

    As Michael says - a reset will most probably fix this.
    Here are instructions on how to do this should you not have your manual handy:
    Click Here - Support Page
    And the iPad Manual:
    Click Here - iPad Manual
    Please let us know how it works out.
    Best of luck..
    Ricky

  • Suggest me the best practise for accesing database by JSP page

    Hi,
    Can you please suggest me the best practises to connect to database through JSP page.
    I am using the Struts-Portlet environment. And I have to display some contents from the database to the jsp page(view.jsp).
    Please suggest.
    Saurabh.

    If you know how to use struts and portlets, you wouldn't be asking this question. I suggest looking into the Model-View Controller pattern to get an idea how to set up a web application, then think about how to do it in a portlet environment.

  • Apps in iPad 1 open and close quickly

    Hello,
    My mother has an iPad 1 (she has her own itunes account) but had never synced and updated her iPad with a computer (pc or mac).
    Today I had to use it and connected to my iTunes on the pc but only to update her iOS on the iPad wich was 3.x. After the whole update process (wich went normal and smooth) almost every app that I woud open, closed imeadtly. I say ALMOST because, a few from the default apps (like Mail, Photos, Safari, System, etc) opens normaly. Though iBooks doesnt and all 3rd party apps also doesnt open normaly.
    I've tryed to reboot it one more time thinking it was some kind of strange bug or something but didn't work. The apps continue to open and close almost instantly.
    I'd like to know if anyone had a similar problem and how they solved it or if my only resource is to roll back to the iPad backup made in my pc.
    Thanks in advance.
    Luis Felipe

    Try double-tapping the home button, then holding the app icon until the minus sign appears. Touch the minus sign to kill all the apps. Then restart the iPad with the home/power buttons (hold for ten seconds) until the apple appears.

  • How can I enable the center mouse click to open and close tabs in Firefox and Chrome?

    I have a MacBook Pro Model A1261 purchased in 2009. On my other mac at work (and my PC) I can center click to open a link in a new tab while in Chrome or FireFox, and also to close a tab by clicking on it in the tabs at the top. I am using an external USB mouse on my MacBook Pro and when I click the center scroll wheel it brings up the dashboard. I looked in the settings but wasn't able to find a way to change that setting for the center button to open and close tabs in my web browser. Is there a way? Please help!

    You can restore the zoom feature by changing the values of the related prefs on the <b>about:config</b> page.
    * browser.gesture.pinch.in -> <b>cmd_fullZoomReduce</b>
    * browser.gesture.pinch.in.shift -> <b>cmd_fullZoomReset</b>
    * browser.gesture.pinch.out -> <b>cmd_fullZoomEnlarge</b>
    * browser.gesture.pinch.out.shift -> <b>cmd_fullZoomReset</b>
    * browser.gesture.pinch.latched -> <b>false</b>
    *http://kb.mozillazine.org/about:config
    See also:
    *pinchy: https://addons.mozilla.org/firefox/addon/pinchy/

  • Open and close multisim contact with LabVIEW

    Can I open and close multisim contact with labview and read the receptor estatus (p.e. lamp)?
    Thanks.
    Attachments:
    Dibujo.JPG ‏13 KB

    Hi Guddan,
    I created a RFC having a query which is taking a long time to execute. So i want to close RFC connection with portals which is via java connector(JCO) before that query and open the connction again after that query.
    I guess i will need to understand your requirement a little more in detail, as i understand you have an RFC which has a query within to fetch some data and is taking a long time to do so. In the meantime you don't want to keep the connection open?
    My question would be, Is the role of this RFC to only execute the query and fetch the data or does it do something else?
    If it does other things and these are independent of the query execution, then you can span a parallel call within the RFC to execute the query and in the meantime the RFC does the other things (or vice versa) hence reducing the overall time taken.
    If the sole purpose of this RFC is to execute the query, then you will not be able(i mean to say there is no simple and direct way of doing this) to close the connection after the Query is started and re-establish the connection after its execution, for a simple reason that - how will you know if the query has completed it's execution, so that you can establish the connection back.
    Alternate solutions, make this a two way asynchronous call, 1) You invoke the RFC asynchronously and close the connection, the RFC in turn will execute the query and transfer the data to JCO via another RFC call.
    If this needs to be a synchronous call, then you will need to optimize the query to its best.
    Regards,
    Chen

Maybe you are looking for