Friday, April 27, 2012

HowTo: Use Oracle / MySQL SQL Commands In UNIX Shell Scripts

How do I call Oracle or MySQL sql statements in UNIX / Linux shell scripts?

You need to use a here document feature supported by sh / bash or ksh. The syntax is as follows:

MySQL: Use SQL Directly In Shell Scripts

#!/bin/sh
user="dbuser"
pass="dbpassword"
db="dbnme"
mysql -u "$user" -p"$pass" "$db" <<EOF
sql-statement-1;
sql-statement-2;
EOF

Using Shell Variables In SQL

#!/bin/sh
user="dbuser"
pass="dbpassword"
db="dbnme"
sql="select * from tal_name"
mysql -u "$user" -p"$pass" <<EOF
use $db;
$sql;
EOF

Oracle: Use SQL Directly In Shell Scripts

#!/bin/sh
user="system"
pass="manager"
sqlplus -S $user/$pass <<EOF
sql-statement-1;
sql-statement-2;
exit;
EOF

Using Shell Variables In SQL

#!/bin/sh
user="system"
pass="manager"
var="$1"
sqlplus -S $user/$pass <<EOF
SELECT * FROM tableName WHERE username=$var;
exit;
EOF
You can call sql statements from .sql file itself as follows:
#!/bin/ksh
sqlplus -S system/manager @my_sql_script.sql

No comments:

Post a Comment