2.5. Example function: query_table.g

This example prints all of the rows of the database tables.

require ("MySQLSupport");

host := "localhost";
user := "test";
password := "";
database := "test_gamma";
tables := list("customers", "suppliers");

function print_query(tbl)
{
  local result = mysql.query_and_store(string("select * from ", tbl));

  princ("Table name: ", tbl, "\n");
  mysql_pretty_print (stdout, result);
  princ("\n");
}

function main ()
{
  local		mysql = new MYSQL();
  
  if (!mysql.connect (host, user, password))
    error (string ("Could not connect to host: ", host,
		   " as user: ", user));
  else if (mysql.select_db (database) == -1)
    error (string ("Could not select database: ", database));

  princ("\n");
  
  with tab in tables do
    print_query(tab);
  
}

Output

Table name: customers
id name                            address             phone        
-- ------------------------------- ------------------- ------------ 
 1 Baker Bob's Pastries            New York            444-555-1212 
 2 Willy Wonka's Chocolate Factory Somewhere in Kansas 222-555-1212 

Table name: suppliers
id name                      address               phone        
-- ------------------------- --------------------- ------------ 
 1 Sugar Hill "North" Farms  Kingston, Jamaica     333-555-1212 
 2 Mack and Molly Milk Farms Clonmacnoise, Ireland 777-555-1212 
 3 Baker Bob's Pastries      New York              111-555-1212