How to directly read database values in shell and assign them to variables

Source: Internet
Author: User
In actual project development, there are many applications that retrieve data from the database. The general solution is to write a data retrieval method. the SQL script is then called and obtained in the shell program. In fact, these two steps can be merged into one step for processing.
For example, if I want to assign all the data queried from Table AA to variable A, the Code is as follows: (PW is the database connection that has been defined)
A = 'sqlplus-S $ PW <EOF
Set heading off
Select * from AA;
Exit
EOF
'
In this way, all data in table AA is assigned to variable A, but note that all information is printed as a row. so whether or not to use this method is still the old method, which depends on the individual's needs (if you only need to query a record, this is feasible)

At the same time, note the MySQL Writing Method collected from the Internet. The above is about Oracle writing. The following code is for reference only:
Since I have set the connection password in/etc/My. CNF, no password is required in both scripts.

Getfrommysql. Sh
# Region #-----------------------------------------------------------------------------------#
#! /Bin/bash
MySQL = 'which mysql'
Dbname = test

Value = '$ mysql $ dbname-u root-se' select * From stars' | sed '1d''
$ Echo "value is..." $ Value
For Val in $ Value
Do
Echo $ Val
Done
# Region #-----------------------------------------------------------------------------------#

Addvaluestomysql. Sh
# Region #-----------------------------------------------------------------------------------#
#! /Bin/bash
MySQL = 'which mysql'
Dbname = test

If [$ #-ne 2]; then
Echo "Usage: Number name"
Else
Statement = "insert into stars values ($1, '$2 ')"
$ Mysql $ dbname-u root <EOF
$ Statement
EOF
If [$? -EQ 0]; then
Echo "add values success"
Else
Echo "add values failed"
Fi
Fi
# Region #-----------------------------------------------------------------------------------#

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.