我有一个具有多个函数的类来处理数据库操作,其中一个用于运行查询(选择、更新、删除、插入......),但我在获取“选择”查询的结果时遇到问题。输出值的格式很奇怪,就好像它们是“列表中的列表”:
这是我的代码中表现奇怪的部分:
# database.connector.py
import logging
import pyodbc
class DBConnector:
...
def _open_cnxn(self) -> pyodbc.Connection:
"""Opens a connection to the database.
Returns:
pyodbc.Connection: Connection object
"""
self.logger.info(f'Openning connection to "{self.server}".')
return pyodbc.connect(self.conn_string)
def _run_query(self, query: str, type: str = "select") -> list:
"""Run the given query
Args:
query (str): query string
type (str, optional): select, insert, update, delete, create. Defaults to "select".
Returns:
list: Query result if select | else commits and returns [None]
"""
try:
cursor = self._open_cnxn().cursor()
self.logger.info(f'Executing query: "{query}".')
cursor.execute(query)
except Exception as error:
self.logger.error(
f'There was an error while trying to execute the query.: "{str(error)}"'
)
# DEBUG
columns = [column[0] for column in cursor.description]
results = [row for row in cursor.fetchall()]
print(columns)
print(results)
# DEBUG
match type:
case "select":
return results
case "insert" | "update" | "delete" | "create":
cursor.commit()
self.logger.info(f"Commited changes to {columns}")
return [None]
我的连接字符串位于
__init__()
内部,如下所示:
self.conn_string = f"DRIVER={{ODBC Driver 17 for SQL Server}}; \
SERVER={self.server}; \
DATABASE={self.database}; \
UID={self.username}; \
PWD={self.password}"
我正在使用带有以下代码的“测试模块”:
# testing.py
import configparser
import logging
import sys
from database.connector import DBConnector
secrets = configparser.ConfigParser()
secrets.read("secrets/config.ini")
SERVER = secrets.get("DB_HOMOLOG", "server")
DATABASE = secrets.get("DB_HOMOLOG", "database")
USERNAME = secrets.get("DB_HOMOLOG", "username")
PASSWORD = secrets.get("DB_HOMOLOG", "password")
connector = DBConnector(
server=SERVER, database=DATABASE, username=USERNAME, password=PASSWORD
)
date_field = "STATUS"
print(connector._run_query("SELECT STATUS FROM TICKETS GROUP BY STATUS"))
该代码的预期结果是这样的列表:
["New", "Ongoing", "Closed", "Canceled", "Solved"]
相反,我收到了这个:
[("New",), ("Ongoing",), ("Closed",), ("Canceled",), ("Solved",)]
我不知道为什么我的值会被这样格式化...有人可以给我一个线索吗?
该代码的预期结果是这样的列表:
["New", "Ongoing", "Closed", "Canceled", "Solved"]
相反,我收到了这个:
[("New",), ("Ongoing",), ("Closed",), ("Canceled",), ("Solved",)]
这是正确的行为。 这里没有错误。
fetchall()
提前不知道您的查询将仅返回一列还是多列,因此为了保持一致性,它将每行结果返回为 tuple。
("New",)
是单元素元组的 Python 表示形式。