LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Running SQL commands from within bash (https://www.linuxquestions.org/questions/linux-newbie-8/running-sql-commands-from-within-bash-823412/)

chirayu11 08-01-2010 01:11 PM

Running SQL commands from within bash
 
Hi

I would be running SQL commands (UPDATE/SELECT) from within my bash script. I am completely new to this subject.

Is MYSQL used for this purpose? Alternatively, what is sqlplus?

Any help appreciated. Thanks.

paulsm4 08-01-2010 01:19 PM

Hi -

You need some kind of "client" in order to talk to your database. This could be a program you write, or a program that comes with the database.

"mysql" is a text-mode client that can talk to a Mysql database. "sqlplus" is a text-mode client that can talk to an Oracle database.

Both mysql and sqlplus can be used from shell scripts - it's just a question of what kind of database you have (i.e. whether you need to communicate with Oracle, with MySql, or with something else).

'Hope that helps .. PSM

AnanthaP 08-02-2010 02:05 AM

mysql is the name for a particular brand of rdbms. sqlplus is the client program for oracle.

In general xsql is the name of the client program (like sqlplus), then you can program like this in your bash script.


Code:

.
.
.
# now invoking sqlplus
sqlplus  datbasename < XX
sqlcommand1
sqlcommand2
.
.
XX
# come out of sqlplus
.
.

Note the XX. It can be any set of characters. But if you start with XX, you must end with XX and bash requires that the ending XX be in column no 1.

EricTRA 08-02-2010 02:23 AM

Hello,

Another example, like I use it in Bash scripts to talk to our database servers:

For Oracle using SQLPLUS:
Code:

sqlplus -s user/password@SID <<EOF
YOUR SQL QUERY;
EOF

For MySQL:
Code:

mysql -udbuser -ppassword -hhostname -v -e 'show slave status\G'
Kind regards,

Eric

chrism01 08-02-2010 05:42 AM

Another method is to just invoke an sql file eg
Code:

mysql -udbuser -ppassword -hhostname <some_file.sql

# where the sql file content might be
select * from some_table;

You can use the same basic idea for most (all?) relational DBs.

chirayu11 08-02-2010 06:31 AM

Hi,

Thanks for all you replies. It really helped.

One further question: I am about to run a handful of SQL commands (update and select) from within my bash script. The database I am using is mysql. I can execute the commands like these:
mysql -uMyUserName -pPassword -DDatabaseName -e "SQLQuery"

But I have several of these queries and I login several times. How do I login just once and execute queries and then log out?

Thanks in advance.

chirayu11 08-02-2010 06:38 AM

Found the answer to my own question. The way to do it is:

Code:

mysql -u[user] -p[pass] -D[dbName] << QUERY_INPUT

#sql commands go here
select id, name from employee;
select crap from table;   

QUERY_INPUT



All times are GMT -5. The time now is 06:11 AM.