| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 | 
							- <?php
 
- namespace App\Service;
 
- use Illuminate\Support\Facades\Config;
 
- use Illuminate\Support\Facades\DB;
 
- use Illuminate\Support\Facades\Log;
 
- class TPlusDatabaseServerService extends Service
 
- {
 
-     public $db = null;
 
-     public $error = null; // 错误信息
 
-     public function __construct()
 
-     {
 
-         $this->createConnection();
 
-     }
 
-     private function createConnection()
 
-     {
 
-         // 主数据库连接
 
-         $mainConnName = 'sqlsrv_main_' . uniqid();
 
-         $mainConfig = [
 
-             'driver' => 'sqlsrv',
 
-             'host' => env('SQLSRV_HOST'),
 
-             'port' => env('SQLSRV_PORT'),
 
-             'database' => env('SQLSRV_DATABASE'),
 
-             'username' => env('SQLSRV_USERNAME'),
 
-             'password' => env('SQLSRV_PASSWORD'),
 
-             'options' => [
 
-                 \PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 30, // SQL Server专用超时
 
-                 \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
 
-             ],
 
-         ];
 
-         Config::set("database.connections.{$mainConnName}", $mainConfig);
 
-         $this->db = DB::connection($mainConnName);
 
-         // 测试连接有效性
 
-         $this->validateConnection($this->db);
 
-     }
 
-     private function validateConnection($connection)
 
-     {
 
-         try {
 
-             $pdo = $connection->getPdo();
 
-             $stmt = $pdo->prepare("SELECT 1 AS connection_test");
 
-             $stmt->execute();
 
-             $result = $stmt->fetch(\PDO::FETCH_ASSOC);
 
-             if (empty($result) || $result['connection_test'] != 1) {
 
-                 $this->error = "T+数据库连接失败";
 
-             }
 
-         } catch (\Throwable $e) {
 
-             $this->error = "T+数据库连接验证失败: " . $e->getMessage();
 
-         }
 
-     }
 
-     public function __destruct()
 
-     {
 
-         // 主动关闭连接
 
-         $this->safeDisconnect($this->db);
 
-     }
 
-     private function safeDisconnect(&$connection)
 
-     {
 
-         try {
 
-             if ($connection instanceof \Illuminate\Database\Connection) {
 
-                 // 物理断开连接
 
-                 $connection->disconnect();
 
-                 // 清除连接引用
 
-                 $connection = null;
 
- //                Log::info("动作", [
 
- //                    'param' => "执行了析构",
 
- //                ]);
 
-             }
 
-         } catch (\Throwable $e) {
 
-             // 静默处理断开错误
 
- //            Log::info("错误", [
 
- //                'param' => $e->getMessage(),
 
- //            ]);
 
-         }
 
-     }
 
- }
 
 
  |