MYSQL.query_to_class

MYSQL.query_to_class — maps query results to class instances.

Syntax

MYSQL.query_to_class (klass, query_string)

Arguments

klass

A class, usually created by a call to mysql_class_from_table.

query_string

A string containing a well-formed SQL query.

Returns

An array of instances of klass.

Description

This method of the MYSQL class emits a query to the database, and maps the results to instances of the class klass, with each row in the query result being used to create a single instance. The query should return 0 or more rows whose columns correspond to the instance variables of klass. This function will throw an error if the class is not defined.

This method is defined in the Gamma library /usr/cogent/require/MySQLSupport.g. It is made available to a Gamma program with the statement: require("MySQLSupport");.

Example

This example is taken from Section 2.2, “Tutorial 2: create_pets.g”

...

  /* Test the MYSQL.query_to_class method. */
  query = mysql.query_to_class (mypetclass, "select * from pets where sex = 'f'");
  pretty_princ ("\nQUERY  The .query_to_class method applied ",
		"to females in mypetclass returns:\n", query, "\n");
  pretty_princ ("The name of the first pet is: ", query[0].name, "\n");

...

The output for this section of the code is as follows:

QUERY  The .query_to_class method applied to females in mypetclass returns:
[{mypetclass (birth . 1993-02-04) (death) (id . 1) (name . Fluffy)
	     (owner . Harold) (sex . f) (species . cat)} 
 {mypetclass (birth . 1998-09-11) (death) (id . 6) (name . Chirpy)
	     (owner . Gwen) (sex . f) (species . bird)}]
The name of the first pet is: Fluffy