The first script, create_db.sh, creates a database called students and a table named students inside it. The mysql command is used for MySQL manipulations. The mysql command specifies the username with -u and the password with -pPASSWORD. The variables USER and PASS are used to store the username and password.
The other command argument for the mysql command is the database name. If a database name is specified as an argument to the mysql command, it will use that database; otherwise, we have to explicitly define the database to be used with the use database_name command.
The mysql command accepts the queries to be executed through standard input (stdin). A convenient way of supplying multiple lines through stdin is using the <<EOF method. The text that appears between <<EOF and EOF is passed to mysql as standard input.
The CREATE DATABASE and CREATE TABLE commands redirect stderr to /dev/null to prevent the display of error messages. The script checks the exit status for the mysql command stored in $? to determine whether a failure has occurred; it assumes that a failure occurs because a table or database already exists. If the database or table already exists, a message is displayed to notify the user; otherwise, the database and table are created.
The write_to_db.sh script accepts the filename of the student data CSV file. It reads each line of the CSV file in the while loop. On each iteration, a line from the CSV file is read and reformatted into a SQL command. The script stores the data from the comma-separated line in an array. Array assignment is done in this form: array=(val1 val2 val3). Here, the space character is the InternalFieldSeparator (IFS). This data has comma-separated values. By changing the IFS to a comma, we can easily assign values to the array (IFS=,).
The data elements in the comma-separated line are id, name, mark, and department. The id and mark values are integers, while name and dept are strings that must be quoted.
The name could contain space characters that would conflict with the IFS. The script replaces the space in the name with a character (#) and restores it after formulating the query.
To quote the strings, the values in the array are reassigned with a prefix and suffixed with \". The tr command substitutes each space in the name with #.
Finally, the query is formed by replacing the space character with a comma and replacing # with a space. Then, SQL's INSERT command is executed.
The third script, read_db.sh, generates a list of students for each department ordered by rank. The first query finds distinct names of departments. We use a while loop to iterate through each department and run the query to display student details in the order of highest marks obtained. SET @i=0 is an SQL construct to set this: i=0. On each row, it is incremented and displayed as the rank of the student.