使用JDBC的简单方式 (但不推荐)

最简单的方式是使用JDBC,就像任何JDBC教程描述的那样,使用java.sql.DriverManager。这里有一个例子,将姓名和电子邮件存入MySQL[65]数据库。

<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=my-password");
      PreparedStatement stmt = null;
      try {
         stmt = conn.prepareStatement("INSERT INTO user values(?, ?)");

         //insert what end user entered into database table
         stmt.set(1, name.value);
         stmt.set(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>

尽管简单,但并不推荐这样做。毕竟ZK应用程序是基于Web的,加载是难以预测且宝贵的资源,例如数据库连接,必须要有效的管理。

很幸运,所有的J2EE框架和Web服务器都支持一种称为连接池(connection pooling)的功能。很容易使用连接池,且用于管理数据库连接更好。在下一章节我们会讨论更多。

[提示]: 不同与其它Web应程序,可以和ZK使用DriverManager,尽管不推荐这样做。

首先,你需要在桌面缓存连接,为每一个事件重复使用此连接,当桌面失效时关闭连接。就像传统的客户端/服务器应用程序一样工作。 就像客户端/服务器应用程序,这样会有效的运作,仅当最多有数十个并发用户时。

为了得知桌面何时失效,你需要通过org.zkoss.zk.ui.util.DesktopCleanup 实现一个监听器。