手动执行正常的ALTER SESSION语句在Python oracledb中报ORA-00922错误
问题描述
我使用Oracle SQL数据库,想要执行语句:
ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD';
该语句在SQL Developer中手动执行完全正常,但使用Python的oracledb模块执行时,出现错误:
Error running SQL script: ORA-00922: missing or invalid option
已确认Python连接Oracle数据库无问题,相关代码如下:
import oracledb import pandas import os import csv import logging import datetime import sys STARTER_QUERY = r"ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD';" Config = {} exec(open("config/info-sql.txt").read(), Config) # print(Config) def get_connection(): connection = oracledb.connect(user=Config["username"], password=Config["password"], dsn=get_dsn(Config['ip'], Config['port'], Config['service_name'])) return connection def run_sql_script(connection, sql_script): try: print(f"SQL script: {sql_script}") logging.info(f"SQL script: {sql_script}") cursor = connection.cursor() cursor.execute(sql_script) columns = [i[0] for i in cursor.description] data = cursor.fetchall() df = pandas.DataFrame(data, columns=columns) return df except Exception as e: print(f"Error running SQL script: {e}") return None connection = get_connection() if connection is None: sys.exit(0) run_sql_script(connection, STARTER_QUERY)
请问是否是字符串格式问题?如何解决?
问题原因与解决方法
- 核心原因:
ALTER SESSION属于DDL语句,执行后不会返回结果集,但当前run_sql_script函数在执行语句后,尝试获取cursor.description并调用fetchall()。没有结果集时cursor.description为None,访问该属性会触发异常,最终表现为ORA-00922错误。 - 解决方式:
- 拆分执行逻辑:将DDL/DML语句与查询语句的执行函数分开,DDL语句无需处理结果集。修改后的DDL执行函数示例:
def run_ddl(connection, sql_script): try: print(f"SQL script: {sql_script}") logging.info(f"SQL script: {sql_script}") cursor = connection.cursor() cursor.execute(sql_script) connection.commit() # DDL语句通常自动提交,显式提交更稳妥 return True except Exception as e: print(f"Error running DDL script: {e}") return None # 调用方式 run_ddl(connection, STARTER_QUERY) - 直接通过oracledb连接属性设置日期格式:无需执行SQL语句,在创建连接时指定参数即可:
connection = oracledb.connect( user=Config["username"], password=Config["password"], dsn=get_dsn(Config['ip'], Config['port'], Config['service_name']), nls_date_format='YYYY-MM-DD' )
- 拆分执行逻辑:将DDL/DML语句与查询语句的执行函数分开,DDL语句无需处理结果集。修改后的DDL执行函数示例:
内容的提问来源于stack exchange,提问作者MSuccessor
相关产品推荐
相关产品推荐

