我经常需要在我的一个数据库中的某个表上运行单个查询,如果不需要的话,我宁愿不必创建一个文件并将其作为脚本和所有内容调用。
我希望能够像这样将查询直接作为字符串发送到 sqlplus
sqlplus user/pass@hostname:port/service "select * from table"
不必创建一个只包含一个查询的文件并调用它
sqlplus user/pass@hostname:port/service @filename
有人知道这是否可能吗?
除了mathguy的回答,还有
linux shells
,
您可以像这样使用运算符here-string
:
sqlplus user/pass@hostname:port/service <<< 'select * from table;'
不要忘记查询末尾的分号。
我相信
sqlplus
命令不接受 SQL 语句(作为字符串)作为命令行参数。您可以交互式或批量运行sqlplus
(提供.sql
文件作为输入)。
但是,您可以使用操作系统功能来执行您所要求的操作。我不知道这在 Windows 中如何工作,但在 Unix/Linux 中你可以使用
here document
。像这样的东西:(为了隐私我屏蔽了我的密码和我的机器名称,但除此之外它是显示命令及其输出的屏幕截图)
[oracle@******** ~]$ sqlplus mathguy/********@orclpdb <<EOF
> select empno, ename, sal
> from scott.emp
> where deptno = 30;
> EOF
SQL*Plus: Release 12.2.0.1.0 Production on Fri Mar 26 15:15:30 2021
Copyright (c) 1982, 2016, Oracle. All rights reserved.
Last Successful login time: Fri Mar 26 2021 15:14:40 -07:00
Connected to:
Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production
SQL> 2 3
EMPNO ENAME SAL
---------- ---------- ----------
7499 ALLEN 1600
7521 WARD 1250
7654 MARTIN 1250
7698 BLAKE 2850
7844 TURNER 1500
7900 JAMES 950
6 rows selected.
SQL> Disconnected from Oracle Database 12c Enterprise Edition Release 12.2.0.1.0
- 64bit Production
[oracle@******** ~]$
永远不要在
sqlplus
命令旁边输入您的凭据,而是通过变量赋值使用/nolog
选项,以便在其他人发出ps
命令时显示它们,例如
rec=$(sqlplus -S /nolog << EOF
conn un/pwd@mydb
set pages 1001
set linesize 500
set feedback off
SELECT * FROM tab;
exit
EOF
)
echo $rec
这是 Windows 版本:
echo select 1 from dual; | sqlplus -s username/password@service
您可以使用它来实现例如Powershell 脚本中的 Docker 健康检查:
$chekdbsql = "`nselect 1 from dual;"
$chkdb = ""
$chkdb = ($chekdbsql | cmd /c "sqlplus username/password@service")
if ($chkdb.Contains("OPEN") -eq 'True'){
Write-Host "0"
}
else {
Write-Host "1"
}