Harnessing the Power of Shell Scripting: Connecting to MySQL, Fetching, and Displaying Results

Shell Scripting @ Freshers.in

Shell scripting allows you to automate a wide range of tasks on Unix-like operating systems. Among the diverse functionalities, it can even help interact with databases like MySQL. In this tutorial, we will demonstrate how to connect to a MySQL database, fetch data from a specific table, and display the results, all using a shell script.

Let’s assume we have a MySQL database and a table freshers_tbl that we wish to interact with.

Step 1: Installing MySQL Client

Firstly, ensure that you have a MySQL client installed on your machine. If not, use the following command to install it (for Ubuntu):

sudo apt-get install mysql-client

Step 2: Writing the Shell Script

Below is a simple shell script that connects to a MySQL database, executes a SQL query on freshers_tbl, and displays the results.

#!/bin/bash

# MySQL server connection details
USER="fr_user_srv_accnt"
PASSWORD="#@12SdfRti$"
DATABASE="freshers_db"
HOST="10.8.123.77"

# SQL query
QUERY='SELECT * FROM freshers_tbl'

# Connect to MySQL server, execute query, and display results
mysql -u $USER -p$PASSWORD -D$DATABASE -h$HOST -e "$QUERY"
Remember to replace the values “USER”, “PASSWORD”, “DATABASE”, and “HOST” with your actual MySQL username, password, database name, and host respectively.
Save this script with a .sh extension (for example, freshers_mysql_connect.sh).

Step 3: Running the Shell Script

Before running the script, you need to grant execution permissions to it using the following command:

chmod +x freshers_mysql_connect.sh
Execute the shell script:
./freshers_mysql_connect.sh

Upon execution, the script will connect to the specified MySQL database and fetch the result from freshers_tbl table and display it on the terminal.

For production environments, consider using protected files, environment variables, or secure services to handle sensitive information like passwords

More similar articles :
Author: user

Leave a Reply