-
Notifications
You must be signed in to change notification settings - Fork 0
Creating Queries | Example
Edward edited this page Nov 21, 2024
·
2 revisions
// Function to fetch the total touchdowns for a specific player
export function getPlayerTouchdowns(playerName) {
return new Promise((resolve, reject) => {
// Define the SQL query
const query = 'SELECT Player, SUM(Touchdowns) as TotalTouchdowns FROM NFL_Player_Stats_1922 WHERE Player = ?';
// Define the parameters for the query
const params = [playerName];
// Execute the query
db.get(query, params, (err, row) => {
if (err) {
// If an error occurs, reject the promise
reject(err);
} else {
// Resolve the promise with the row result
resolve(row);
}
});
});
}export function getPlayerTouchdowns(playerName) {- Declares a named function
getPlayerTouchdownsthat accepts a parameterplayerName. - The
exportkeyword allows this function to be imported in other files. - The purpose of this function is to retrieve the total touchdowns for a given player.
return new Promise((resolve, reject) => {- Since SQLite operates asynchronously, this function returns a
Promiseto handle the operation. - The
resolvefunction will return the query result if it succeeds, whilerejectwill handle any errors.
const query = 'SELECT Player, SUM(Touchdowns) as TotalTouchdowns FROM NFL_Player_Stats_1922 WHERE Player = ?';- Defines an SQL query string to fetch the player's name and calculate the sum of their touchdowns (
SUM(Touchdowns)). - The
?is a placeholder for parameters, which prevents SQL injection attacks.
const params = [playerName];- An array containing
playerName, which will replace the?in the query. This ensures safe parameter binding.
db.get(query, params, (err, row) => {- The
db.getmethod executes the query and fetches a single row of results. - It takes the query string, parameters, and a callback function that processes the result.
if (err) {
reject(err);
}- If an error occurs during query execution, the
rejectfunction is called with the error object.
resolve(row);- If the query is successful, the
resolvefunction is called with the result (row), which contains the player's name and total touchdowns.
async function fetchPlayerTouchdowns(playerName) {
try {
const result = await window.api.getPlayerTouchdowns(playerName);
console.log(`${result.Player} has a total of ${result.TotalTouchdowns} touchdowns.`);
} catch (error) {
console.error('Error fetching player touchdowns:', error);
}
}
fetchPlayerTouchdowns('John Doe');