views:

2615

answers:

5

I have some SQL scripts that I'm trying to automate. In the past I have used SQL*Plus, and called the sqlplus binary manually, from a bash script.

However, I'm trying to figure out if there's a way to connect to the DB, and call the script from inside of the bash script... so that I can insert date and make the queries run relative to a certain number of days in the past.

+1  A: 

Why can't you just use something like a small Java program and pass in the arguments you need?

dbrien
You expose yourself to getting voted down - use the comment feature next time.
OMG Ponies
I'd go with a perl script (which is installed along with oracle) rather than java, but support the dbrien's "I wouldn't start from here" approach.
Gary
+3  A: 

I'm slightly confused. You should be able to call sqlplus from within the bash script. This may be what you were doing with your first statement

Try Executing the following within your bash script:

#!/bin/bash          
echo Start Executing SQL commands
sqlplus <user>/<password> @file-with-sql-1.sql
sqlplus <user>/<password> @file-with-sql-2.sql

If you want to be able to pass data into your scripts you can do it via SQLPlus by passing arguments into the script:

Contents of file-with-sql-1.sql

 select * from users where username='&1';

Then change the bash script to call sqlplus passing in the value

#!/bin/bash

MY_USER=bob
sqlplus <user>/<password> @file-with-sql-1.sql $MY_USER
RC
A: 

As Bash doesn't have built in sql database connectivity... you will need to use some sort of third party tool.

instanceofTom
A: 

Here is a simple way of running MySQL queries in the bash shell

mysql -u [database_username] -p [database_password] -D [database_name] -e "SELECT * FROM [table_name]"

GeekTantra
The OP is using Oracle.
OMG Ponies
A: 

Maybe you can pipe SQL query to sqlplus. It works for mysql:

echo "SELECT * FROM table" | mysql --user=username database
danadam