Home > Net >  How to run SQL connection within variable with second SQL query
How to run SQL connection within variable with second SQL query

Time:08-10

Apologies if the title is unclear, I am not sure how to explain it.

I have the following variable made, which is basically one that I can put in a script and use to run SQL queries from within the terminal where needed:

use_sql= psql -U TravelOwner -d TravelDB -c

An example of how I would use this variable is as follows:

$use_sql 'SELECT * FROM country'

This makes it that I don't have to keep writing the full psql command everytime. The desired result is that it should run is if it says, this query runs fine from the terminal:

psql -U TravelOwner -d TravelDB -c 'SELECT * FROM country'

Thanks for any help

CodePudding user response:

The most logical way to prevent repeating stuffs in any programming languages, is by using functions or named procedures:

#!/usr/bin/env bash

db_query()
{
  psql -U TravelOwner -d TravelDB -c "$1"
}

# Then use the function to perform various queries
db_query 'SELECT * FROM country;'
  • Related