Connect and Close a Connection

After configuring connection pooling (which will be discussed in the following section), you could use JNDI to retrieve an connection as follows.

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.zkoss.zul.Window;

public class MyWindows extends Window {
    private Textbox name, email;    
    public void onCreate() {    
        //initial name and email        
        name = getFellow("name");        
        email = getFellow("email");        
    }    
    public void onOK() throws Exception {    

DataSource ds = (DataSource)new InitialContext()

.lookup("java:comp/env/jdbc/MyDB");

//Assumes your database is configured and            
            //named as "java:comp/env/jdbc/MyDB"            

        Connection conn = null;        
        Statement stmt = null;        
        try {        

conn = ds.getConnection();

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();            
            stmt.close(); stmt = null;            
                //optional because the finally clause will close it                
                //However, it is a good habit to close it as soon as done, especially                 
                //you might have to create a lot of statement to complete a job                
        } finally { //cleanup        
            if (stmt != null) {            
                try {                
                    stmt.close();                    
                } catch (SQLException ex) {                
                    //(optional log and) ignore                    
                }                
            }            
            if (conn != null) {            
                try {                
                    conn.close();                    
                } catch (SQLException ex) {                
                    //(optional log and) ignore                    
                }                
            }            
        }        
    }    
}

Notes: