Running Your Own SQL

A convenient way to use the same database connection techniques as KonaKart is as follows:

First a SELECT query... note the processing of the result set after the results are returned.


/*
 * Run a query that selects the product id and product model from
 * all products that have an id less than 10. All Select queries 
 * need to be run using the KKBasePeer.executeQuery command
 */

List<Record> records = KKBasePeer
      .executeQuery("select products_id, products_model, " +
                           "products_price " +
                           "from products " +
                           "where products_id < 10");

/*
 * Loop through the result set and print out the results. Note that
 * the first attribute in the Record object is at index = 1 and not
 * index = 0
 */

if (records != null)
{
    for (Iterator<Record> 
         iterator = records.iterator(); 
         iterator.hasNext();)
    {
        Record rec = (Record) iterator.next();
        System.out.println("id = " + rec.getValue(1).asInt() 
                    + "; model = "
                    + rec.getValue(2).asString() + "; price = "
                    + rec.getValue(3).asBigDecimal(/* scale */2));
    }
}

Here's a simple UPDATE example:


/*
 * Now let's run another query to change the model name of the
 * product with id = 1. 
 *
 * All non select queries need to be run using the 
 * KKBasePeer.executeStatement command
 */

KKBasePeer.executeStatement(
        "update products set products_model='Super Turbo' where products_id=1");

The /java_api_examples/src/com/konakart/apiexamples/RunCustomQuery.java example, provided in the download kit, illustrates this technique.