PCM_Report/test_sqlserver_in_exe.py

147 lines
3.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
测试打包后的SQL Server连接
在打包后的exe中运行此脚本来诊断SQL Server连接问题
"""
import sys
import os
print("=" * 80)
print("SQL Server 连接诊断工具")
print("=" * 80)
print()
# 检查运行环境
if getattr(sys, 'frozen', False):
print("✓ 运行在打包后的环境中")
print(f" 基础路径: {sys._MEIPASS}")
else:
print("✓ 运行在开发环境中")
print(f" 当前路径: {os.getcwd()}")
print()
# 测试pymssql
print("-" * 80)
print("测试 pymssql")
print("-" * 80)
try:
import pymssql
print("✓ pymssql 导入成功")
print(f" 版本: {pymssql.__version__}")
print(f" 路径: {pymssql.__file__}")
# 检查_mssql模块
try:
import _mssql
print("✓ _mssql 模块导入成功")
except Exception as e:
print(f"✗ _mssql 模块导入失败: {e}")
except Exception as e:
print(f"✗ pymssql 导入失败: {e}")
import traceback
traceback.print_exc()
print()
# 测试pyodbc
print("-" * 80)
print("测试 pyodbc")
print("-" * 80)
try:
import pyodbc
print("✓ pyodbc 导入成功")
print(f" 版本: {pyodbc.version}")
print(f" 路径: {pyodbc.__file__}")
# 列出可用的ODBC驱动
try:
drivers = pyodbc.drivers()
print(f"✓ 可用的ODBC驱动 ({len(drivers)}个):")
for driver in drivers:
print(f" - {driver}")
except Exception as e:
print(f"✗ 无法列出ODBC驱动: {e}")
except Exception as e:
print(f"✗ pyodbc 导入失败: {e}")
import traceback
traceback.print_exc()
print()
# 测试连接(如果提供了连接信息)
print("-" * 80)
print("测试实际连接")
print("-" * 80)
print("请输入SQL Server连接信息直接回车跳过:")
print()
server = input("服务器地址 (例如: localhost 或 192.168.1.100): ").strip()
if server:
database = input("数据库名称: ").strip()
username = input("用户名: ").strip()
password = input("密码: ").strip()
print()
print("尝试使用 pymssql 连接...")
try:
conn = pymssql.connect(
server=server,
database=database,
user=username,
password=password,
timeout=5
)
print("✓ pymssql 连接成功!")
conn.close()
except Exception as e:
print(f"✗ pymssql 连接失败: {e}")
print()
print("尝试使用 pyodbc 连接...")
try:
# 尝试不同的驱动
drivers_to_try = [
"ODBC Driver 17 for SQL Server",
"ODBC Driver 18 for SQL Server",
"SQL Server Native Client 11.0",
"SQL Server"
]
connected = False
for driver in drivers_to_try:
try:
conn_str = (
f"DRIVER={{{driver}}};"
f"SERVER={server};"
f"DATABASE={database};"
f"UID={username};"
f"PWD={password};"
"TrustServerCertificate=yes;"
)
conn = pyodbc.connect(conn_str, timeout=5)
print(f"✓ pyodbc 连接成功!使用驱动: {driver}")
conn.close()
connected = True
break
except Exception as e:
print(f" 尝试驱动 '{driver}' 失败: {e}")
if not connected:
print("✗ pyodbc 所有驱动都连接失败")
except Exception as e:
print(f"✗ pyodbc 连接失败: {e}")
else:
print("跳过连接测试")
print()
print("=" * 80)
print("诊断完成")
print("=" * 80)
print()
# 如果在打包环境中,等待用户按键
if getattr(sys, 'frozen', False):
input("按回车键退出...")