不断收到数据库错误:ORA-00933:SQL命令未正确结束,没有任何解释

问题描述 投票:0回答:1

我正在尝试使用以下代码从 python 中的 Oracle DB 中读取数据:

conn: SqlConnection
# conn_info = DotenvSqlConnection.get_connection_info(add_env_to_connection_id(ConnectionList.Oracle, forced_env_type=EnvironmentType.Dev))
conn_info = conn.get_connection_info(add_env_to_connection_id(ConnectionList.Oracle, forced_env_type=EnvironmentType.Dev))
host_Or= conn_info.host
service_or=conn_info.service
user_id_or=conn_info.user
password_or= conn_info.password
port_or = conn_info.port


print(host_Or, service_or, user_id_or, password_or, port_or)
connection_string = f"{user_id_or}/{password_or}@{host_Or}:{port_or}/{service_or}"
cnxn = cx_Oracle.connect(connection_string)
cursor = cnxn.cursor()

cursor = cnxn.cursor()
table = 'myTable'
account_query = f'''
                SELECT a.*
                FROM my_user.{table} a
                FETCH FIRST 4333 ROWS ONLY
                ORDER BY a.ACCNT_ID;
                '''
cursor.execute(account_query) 
row = cursor.fetchone() 

# Print the count value (number of rows)
if row:
    row_count = row[0]
    print("Number of rows:", row_count)
else:
    print("No rows found.")

但我不断收到以下错误:

----> 9 cursor.execute(account_query) 
     10 row = cursor.fetchone() 
     12 # Print the count value (number of rows)

DatabaseError: ORA-00933: SQL command not properly ended

我尝试了很多方法来解决它,但它不断出现。任何建议都会非常感谢!

python oracle cx-oracle
1个回答
0
投票

SQL 语句中的空格可能是一个问题。

试试这个:

account_query = f'''
                SELECT a.*
                FROM my_user.{table} a
                FETCH FIRST 4333 ROWS ONLY
                ORDER BY a.ACCNT_ID;
                '''
t = str.maketrans({"\n": " ", "\t": " "})
cursor.execute(account_query.translate(t).strip())

或者:

import re

account_query = f'''
                SELECT a.*
                FROM my_user.{table} a
                FETCH FIRST 4333 ROWS ONLY
                ORDER BY a.ACCNT_ID;
                '''
cursor.execute(re.sub(r"[\s\t\n]+", " ", account_query.strip()))
© www.soinside.com 2019 - 2024. All rights reserved.