【问题标题】:Executing a SQL*Plus .sql file in Python for Oracle Database在 Python 中为 Oracle 数据库执行 SQL*Plus .sql 文件
【发布时间】:2019-11-09 11:22:03
【问题描述】:

大家好,我有这个 sql 文件:

Student.sql

Select * from student where age > 18;

Delet student_ name , studen_id if age > 18 ;
Commit; 

使用 cx_oracle pip 任何帮助

【问题讨论】:

  • 您不能直接在 Python 解释器中执行 SQL 代码。 Python 解释器不是 SQL 引擎。您需要将其包装起来(通常以字符串形式),然后将该字符串发送到 SQL 引擎以执行。有一些图书馆可以做到这一点,比如cx_Oracle
  • 我知道这一点,但使用 cx_oracle 我可以找到 .sql 并执行它
  • 不确定你在问什么,因为你的问题似乎是“在 python 中执行 .sql 文件”。如果你知道你不能那样做,为什么还要问呢?也许更新你的问题,问你想知道什么。

标签: python python-3.x oracle cx-oracle


【解决方案1】:

您可以执行在代码中定义的查询,而不是执行文件。

import cx_Oracle

dsn_tns = cx_Oracle.makedsn('Host Name', 'Port Number', service_name='Service Name') #if needed, place an 'r' before any parameter in order to address any special character such as '\'.
conn = cx_Oracle.connect(user=r'User Name', password='Personal Password', dsn=dsn_tns) #if needed, place an 'r' before any parameter in order to address any special character such as '\'. For example, if your user name contains '\', you'll need to place 'r' before the user name: user=r'User Name'
query = """
        Select * from student where age > 18;
        DeletE student_ name , studen_id if age > 18 
        """
c = conn.cursor()
c.execute(query) # use triple quotes if you want to spread your query across multiple lines
print('Result', c)
#conn.close()

【讨论】:

  • 您可以在 Oracle 中运行以下查询以获取服务名称: select sys_context('userenv','service_name') from dual 您也可以在 Oracle 中运行以下查询以获取用户列表: 从 dba_users 中选择用户名
  • 非常感谢您的快速回答,但我有 400 行代码.. 我只是想是否可以直接执行文件 .sql。 :)
  • f = open("run_all_su.sql") full_sql = f.read() sql_commands = full_sql.split(';') #sql_commands = full_sql.replace('\n', '') .split(';')[:-1] # 只带 [] 为空 print(sql_commands) for sql_command in sql_commands: print(sql_command) cur.execute(sql_command)
【解决方案2】:

正如其他回复所指出的,您一次只能使用 cx_Oracle 执行一条语句。但是,您可以编写一个包装器来读取您的 SQL 文件并执行每个语句。如果您限制 SQL 语法(特别是关于行终止符),这会容易得多。示例见https://github.com/oracle/python-cx_Oracle/blob/master/samples/SampleEnv.py#L116

【讨论】:

    猜你喜欢
    • 2016-12-26
    • 2021-12-28
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2011-03-01
    • 2011-07-04
    • 1970-01-01
    相关资源
    最近更新 更多