Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

Bash Oracle connection execute multiple queries

I am new in programming oracle in bash and I have to create a function which reads a CSV and updates a table in an Oracle DB, which is working so far. I have used the tutorial from here: https://zwbetz.com/connect-to-an-oracle-database-and-run-a-query-from-a-bash-script/

The code is:

export ORACLE_SID=$OSID
export ORACLE_HOST=$HOST
export ORACLE_PORT=$PORT
export ORACLE_DATABASE=$DB
export ORACLE_USERNAME=$USER 
export ORACLE_PASSWORD=$PW

while IFS="|" read -r col1, col2, col3; do
    sql="INSERT INTO my_table(col1, col2, col3)
                VALUES ('$col1',
                        '$col2', 
                        '$col3');"
    echo -e "SET PAGESIZE 0
 SET FEEDBACK ON
 $sql" | 
    sqlplus -S -L "$ORACLE_USERNAME/$ORACLE_PASSWORD@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$ORACLE_HOST)(PORT=$ORACLE_PORT))(CONNECT_DATA=(SERVICE_NAME=$ORACLE_DATABASE)))"
    
done < $INPUT_ADD

The query is send with this commando:

echo -e "SET PAGESIZE 0
 SET FEEDBACK ON
 $sql" | 
    sqlplus -S -L "$ORACLE_USERNAME/$ORACLE_PASSWORD@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$ORACLE_HOST)(PORT=$ORACLE_PORT))(CONNECT_DATA=(SERVICE_NAME=$ORACLE_DATABASE)))"

What I am not sure about is, is sqlplus always opening for each execution of the query a new DB connection? And if so, is it posible to leave the connection open and close the connection when the while loop finished?

Thank you for your help!

question from:https://stackoverflow.com/questions/66060884/bash-oracle-connection-execute-multiple-queries

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can generate the sql-file containing all your inserts in the while loop and at the end, outside the loop, call sqlplus with the file as input. Now you only connect once.

A more one-liner *nix approach would be:

awk '{transform-magic}' file.csv | sqlplus <connect-info>

But I rather recommend existing tools for the job.

Best of luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...