python - 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)
解决方案
在 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 - python中变量/函数捕获背后的机制是什么?
- javascript - 如何将随机整数放入 HTML 和 js 中的表格中
- windows - 将 PS 配置文件添加到新的本地用户
- angular - 如何使用 Angular cli 在 Angular 项目设置中更改 webpack.config 文件
- bash - 詹金斯管道:带有参数的sh mv不起作用
- php - 如何返回 $this->address[$type] ?[]; 工作?
- javascript - 如何使用 Javascript 每天在特定时间重新加载 URL?
- python - 在 Tesseract 中保留空间
- python - 将字符串拆分为两个单词的列表,重复最后一个单词
- json - 使用 scala 将 JSON 平面嵌套到标题级别