Python中的SQL查询格式

Python中的SQL查询格式,python,sql,oracle,cx-oracle,Python,Sql,Oracle,Cx Oracle,我想查询我的Oracle数据库,但它不工作。我想我在格式方面遗漏了一些东西,但无法理解。 如果我在SQLDeveloper中执行相同的查询,它将返回结果。但在Python中,它给出了“SyntaxError:invalid syntax.”错误 import os import cx_Oracle import matplotlib.pyplot as plt import numpy as np dsn_tns = cx_Oracle.makedsn('host', '1521', serv

我想查询我的Oracle数据库,但它不工作。我想我在格式方面遗漏了一些东西,但无法理解。 如果我在SQLDeveloper中执行相同的查询,它将返回结果。但在Python中,它给出了“SyntaxError:invalid syntax.”错误

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)

如果您使用的是
groupby
,则不必使用
DISTINCT
,因为前者已经确保您将获得不同的结果。此外,您可能希望按照整个select表达式(
ltrim
…)进行分组,而不仅仅是
id
,即

SELECT ltrim(regexp_substr(id, '[0-9]{3,}'), '0') AS reportid,
       COUNT(id)
FROM dev_user.record_table
GROUP BY ltrim(regexp_substr(id, '[0-9]{3,}'), '0')

最后,你说

在Python中,它给出了一个错误


哪个错误?

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

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

Python中的错误是什么?数据库在localhost中,错误是-SyntaxError:invalid syntaxe引用有问题。第一个带引号的字符串是
'selectdistinct(LTRIM)(REGEXP_SUBSTR(ID),
),因此我希望解析器在它之后的任何事情上都会抱怨,从
[0-9]{3,}
.SyntaxError:无效语法。这是我遇到的错误。尝试使用相同的语法,SyntaxError:无效语法。出现错误。是否有错误代码?类似于ORA-01234或PLS-01234或类似的代码?因为SELECT语句本身看起来正常,并且在我的Oracle 11gXE数据库中正常工作。也许您可以删除username从from子句中删除,这样当您作为DEV_用户连接时,它看起来是“从记录_表”。这解决了问题。谢谢Chris。