首页 > 解决方案 > Python中的SQL查询格式化

问题描述

我想查询我的 Oracle DB,但它不工作。我想我在格式上遗漏了一些东西,但无法弄清楚。如果我在 SQL 开发人员中执行相同的查询,它会返回结果。但在 Python 中,它给出了“SyntaxError:无效语法”。错误。

import os
import cx_Oracle
import matplotlib.pyplot as plt
import numpy as np

dsn_tns = cx_Oracle.makedsn('host', '1521', service_name='S1') 
conn = cx_Oracle.connect(user=r'dev_user', password='Welcome', dsn=dsn_tns) 


reportid_count = []
count_ID =  []

c = conn.cursor()

query = 'select distinct (LTRIM(REGEXP_SUBSTR(ID, '[0-9]{3,}'), '0')) as ReportID,count(ID) from dev_user.RECORD_TABLE  group by ID'
c.execute(query) 


#loop through the rows fetched and store the records as arrays.
for row in c:
    reportid_count.append(row[0] + ',' + str(row[1]))
    count_ID.append(row[1])

for s in reportid_count:
    print(s)

标签: pythonsqloraclecx-oracle

解决方案


在 Python 方面,您需要删除嵌入的引号。尝试使用:

query = """select distinct (LTRIM(REGEXP_SUBSTR(ID, '[0-9]{3,}'), '0')) as ReportID,count(ID) from dev_user.RECORD_TABLE  group by ID"""

推荐阅读