Simplest Way to Use JDBC (but not recommended)

From Documentation
Revision as of 03:59, 19 July 2010 by Char (talk | contribs)
Simplest Way to Use JDBC (but not recommended)


Stop.png This documentation is for an older version of ZK. For the latest one, please click here.


The simplest way to use JDBC, like any JDBC tutorial might suggest, is to use java.sql.DriverManager. Here is an example to store the name and email into a MySQL database.

<window title="JDBC demo" border="normal">
     <zscript><![CDATA[
     import java.sql.*;
     void submit() {
         //load driver and get a database connetion
         Class.forName("com.mysql.jdbc.Driver");
         Connection conn = DriverManager.getConnection(
             "jdbc:mysql://localhost/test?user=root&password=R3f@ct0r");
         PreparedStatement stmt = null;
         try {
             stmt = conn.prepareStatement("INSERT INTO user values(?, ?)");
 
             //insert what end user entered into database table
             stmt.setString(1, name.value);
             stmt.setString(2, email.value);
 
             //execute the statement
             stmt.executeUpdate();
         } finally { //cleanup
             if (stmt != null) {
                 try {
                     stmt.close();
                 } catch (SQLException ex) {
                     log.error(ex); //log and ignore
                 }
             }
             if (conn != null) {
                 try {
                     conn.close();
                 } catch (SQLException ex) {
                     log.error(ex); //log and ignore
                 }
             }
         }
     }
     ]]>
     </zscript>
     <vbox>
         <hbox>Name : <textbox id="name"/></hbox>
         <hbox>Email: <textbox id="email"/></hbox>
         <button label="submit" onClick="submit()"/>
     </vbox>
 </window>

Though simple, it is not recommended. After all, ZK applications are Web-based applications, where loading is unpredictable and treasurable resources such as database connections have to be managed effectively.

Luckily, all J2EE frameworks and Web servers support a utility called connection pooling. It is straightforward to use, while managing the database connections well. We will discuss more in the next section.

Tip: Unlike other Web applications, it is possible to use DriverManager with ZK, though not recommended.

First, you could cache the connection in the desktop, reuse it for each event, and close it when the desktop becomes invalid. It works just like traditional Client/Server applications. Like Client/Server applications, it works efficiently only if there are at most tens concurrent users.

To know when a desktop becomes invalid, you have to implement a listener by use of DesktopCleanup.



Last Update : 2010/07/19

Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.