Shell Script connects Oracle database
Recently studied how to use shell script to connect to the database, and then execute the query statement. So for the script that needs to be executed regularly, we can build a crontab to execute it regularly.
First, the installation of the client: Linux environment needs to use Sqlplus client to connect Oracle database, first we need to confirm that there is no installation: which sqlplus if not installed on the need to install first, the installation steps are as follows:
Download to the Oracle website, then install the following two modules:
RPM-IVH oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
RPM-IVH oracle-instantclient11.2-sqlplus-11.2.0.3.0-1.x86_64.rpm
To configure environment variables:
Vim/etc/profile
After saving, execute: source/etc/profile
Whereis Oracle #查看oracle Client Installation path
Access to the client directory
Add configuration file: Touch Tnsnames.ora
Edit configuration file: Vim Tnsnames.ora
DATABASENAME =
(DESCRIPTION = (
address_list =
(address = (PROTOCOL = TCP) (HOST = 127.0.0.1) (PORT = 1521))
)
(Connect_data =
(service_name = ServiceName)
)
)
After the edit save completes, you can use the command line to test whether the connection succeeded
Sqlplus Username/password@databasename
If normal, you can successfully connect to the Oracle database.
So we're going to start writing our own shell script:
#! /bin/bash
sqlplus username/password@databasename >tmp.txt << EOF
set heading off
set line 4000
set WRAP
off Select user_id,mobile from Txlx_xxx_user_info Where rownum <20;
Exit
EOF
sed-i 1,12d tmp.txt
sed-i-E '/selected/, $d ' tmp.txt
sed-i-E '/disconnected/, $d ' Tmp.txt
sed-i ' $d ' tmp.txt
Explain this line by row:
#!/bin/bash #shell script, specify which shell to use to
connect to the database statement, standard output to tmp.txt, get input from <<eof,
remove header
set row width
Turn off word wrap
query statement
exit
EOF input end
sed delete tmp.txt 1~12 row Connection Database text Delete
selected to the last line of text
deletion Disconnected to the last line of text
delete the last line of text