A simple way of testing if the connection works is by executing a trivial query that returns a constant value; what really matters here is that the function should work without throwing any exceptions. We use await to get the result of the .query() method, that is an array with all the found rows; in this case, the array will obviously have a single row:
// ...continued
async function tryDbAccess(dbConn) {
try {
const rows = await dbConn.query("SELECT 1960 AS someYear");
console.log(`Year was ${rows[0].someYear}`);
} catch (e) {
console.log("Unexpected error", e);
}
}
// continues...
Let's try something else: what about finding the ten countries that have more cities? We can use .forEach() to list the results in a frankly not-very-attractive format:
// ...continued
async function get10CountriesWithMoreCities(dbConn) {
try {
const myQuery = `SELECT
CI.countryCode,
CO.countryName,
COUNT(*) as countCities
FROM cities CI JOIN countries CO
ON CI.countryCode=CO.countryCode
GROUP BY 1
ORDER BY 3 DESC
LIMIT 10`;
const rows = await dbConn.query(myQuery);
rows.forEach(r =>
console.log(r.countryCode, r.countryName, r.countCities)
);
} catch (e) {
console.log("Unexpected error", e);
}
}
// continues...