Recipe 3.4. Using Column Aliases to Make Programs Easier to WriteProblem
You're trying to refer to a column by name from within a program, but the column is calculated from an expression. Consequently, its
SolutionUse an alias to give the column a simpler name. Discussion
Section 3.3 shows how column aliases make query results more meaningful when you're issuing queries interactively. Aliases also are useful for programming purposes. If you're writing a program that fetches rows into an array and
$sth = $dbh->prepare ("SELECT srcuser,
DATE_FORMAT(t,'%M %e, %Y') AS date_sent
FROM mail");
$sth->execute ();
while (my $ref = $sth->fetchrow_hashref ())
{
printf "user: %s, date sent: %s\n", $ref->{srcuser}, $ref->{date_sent};
}
In Java, you'd do something like this, where the argument to getString( ) names the column containing the value that you want to access:
Statement s = conn.createStatement ();
s.executeQuery ("SELECT srcuser,"
+ " DATE_FORMAT(t,'%M %e, %Y') AS date_sent"
+ " FROM mail");
ResultSet rs = s.getResultSet ();
while (rs.next ()) // loop through rows of result set
{
String name = rs.getString ("srcuser");
String dateSent = rs.getString ("date_sent");
System.out.println ("user: " + name + ", date sent: " + dateSent);
}
rs.close ();
s.close ();
In Ruby, rows can be
See AlsoSection 2.4 shows for each of our programming languages how to fetch rows into data structures that enable you to access columns values by column name. Also, the select directory of the recipes directory has examples that show how to do this for the mail table. |
Recipe 3.5. Combining
|