Simplest Way to Use JDBC (but not recommended)

From Documentation
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">
     import java.sql.*;
     void submit() {
         //load driver and get a database connetion
         Connection conn = DriverManager.getConnection(
         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
         } finally { //cleanup
             if (stmt != null) {
                 try {
                 } catch (SQLException ex) {
                     log.error(ex); //log and ignore
             if (conn != null) {
                 try {
                 } catch (SQLException ex) {
                     log.error(ex); //log and ignore
         <hbox>Name : <textbox id="name"/></hbox>
         <hbox>Email: <textbox id="email"/></hbox>
         <button label="submit" onClick="submit()"/>

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 : 2022/01/19

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