You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类初始化执行无输出:SQL Server查询脚本故障排查

问题排查与修复

我通过读取独立配置文件中的凭据连接SQL Server,选择需要查询的表并执行SELECT *操作。运行代码时无报错,但未打印出预期的“Successfully connected to database”日志及SELECT语句输出,怀疑未正确初始化类或函数,请问问题出在哪里?

用户提供的代码

import pyodbc
import logging
import json

class UpdateTables:

    def connect_db(self):
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)

        with open(r'scriptpath\\config_file.json','r') as ts:
            config = json.load(ts)

        self.driver = config['driver']
        self.server = config['server']
        self.database = config['database']

        try:
            conn = pyodbc.connect(
            f'Driver={self.driver};'
            f'Server={self.server};'
            f'Database={self.database};'
            )

            logger.info("Successfully connected to database")

        except Exception as e:
            logger.error("Unable to connect to database: %s", str(e))

        return conn

    def read_query(self, conn):
        try:
            cursor = conn.cursor()
            read_table_query="""
                SELECT TOP 2 table_name
                FROM information_schema.tables;
                """
            cursor.execute(read_table_query)              

            for tables in cursor.fetchall():
                tab = tables[0]
                write_table_query = f'SELECT TOP 10 * FROM {tab};'
                print(write_table_query)
                print(cursor.fetchall())
                cursor.execute(write_table_query)

        except Exception as e:
            logging.exception(e)

        return cursor

核心问题分析

1. 日志模块未配置输出Handler

logging模块默认没有绑定输出渠道,仅设置日志级别不会将日志内容打印到控制台,所以logger.info和logger.error的内容无法显示。

2. 缺少程序执行入口

代码仅定义了类和方法,但没有实例化类、调用方法的逻辑——相当于只写了功能模板,根本没触发任何实际执行。

3. 游标操作逻辑错误

  • 循环中cursor.fetchall()已取完表名查询的结果,游标移至末尾,此时再调用print(cursor.fetchall())会返回空列表。
  • 执行write_table_query后,没有再次获取并打印查询结果,所以看不到表数据的输出。

修复后的完整代码

import pyodbc
import logging
import json

class UpdateTables:

    def __init__(self):
        # 初始化日志,添加控制台输出Handler
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        # 避免重复添加Handler
        if not logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            handler.setFormatter(formatter)
            logger.addHandler(handler)

    def connect_db(self):
        logger = logging.getLogger()

        with open(r'scriptpath\\config_file.json','r') as ts:
            config = json.load(ts)

        self.driver = config['driver']
        self.server = config['server']
        self.database = config['database']

        try:
            conn = pyodbc.connect(
            f'Driver={self.driver};'
            f'Server={self.server};'
            f'Database={self.database};'
            )
            logger.info("Successfully connected to database")
            return conn
        except Exception as e:
            logger.error("Unable to connect to database: %s", str(e))
            # 连接失败返回None,避免后续报错
            return None

    def read_query(self, conn):
        if not conn:
            logging.error("Invalid database connection")
            return None
            
        try:
            cursor = conn.cursor()
            read_table_query="""
                SELECT TOP 2 table_name
                FROM information_schema.tables;
                """
            cursor.execute(read_table_query)              
            # 先存储表名结果,避免游标移动后无法获取
            tables = cursor.fetchall()

            for table in tables:
                tab = table[0]
                write_table_query = f'SELECT TOP 10 * FROM {tab};'
                print(write_table_query)
                cursor.execute(write_table_query)
                # 获取并打印当前查询的结果
                results = cursor.fetchall()
                print(results)

            return cursor
        except Exception as e:
            logging.exception(e)
            return None

# 程序入口:实例化类并执行方法
if __name__ == "__main__":
    updater = UpdateTables()
    db_conn = updater.connect_db()
    if db_conn:
        updater.read_query(db_conn)
        # 关闭数据库连接
        db_conn.close()

修复说明

  1. 在类的__init__方法中添加日志的控制台输出Handler,确保日志能正常显示,同时避免重复添加Handler。
  2. 添加if __name__ == "__main__"作为程序入口,实例化类并依次调用连接、查询方法。
  3. 修正游标逻辑:先存储表名查询结果,循环时直接使用;执行表数据查询后立即获取并打印结果;增加连接有效性判断,避免空连接报错;连接失败时返回None,后续逻辑做容错处理。

内容的提问来源于stack exchange,提问作者postgreshelp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:07:51