1. 程式人生 > >thinkphp5 連線 SqlServer 執行儲存過程,返回為空解決方案

thinkphp5 連線 SqlServer 執行儲存過程,返回為空解決方案

專案做在win下,伺服器是類似空間伺服器,所以不可以裝擴充套件,只能yum

老闆又非要用雙資料庫(sqlsever 心酸里程) ,結果就是伺服器sqlsrv 不可用,裝的是dblib  ......云云雲

水準不高 ,只能用最簡單的方法 。

貼程式碼記錄一下,返回結果成功 ,程式碼copy修改,其中有些不懂的地方 或者還有更好的方法,隨時歡迎賜教

修改配置檔案 database.php

'db2'   => [
        //本地
        'type'            => 'sqlsrv',
        // 伺服器地址
        'hostname'        => '127.0.0.1',
        // 資料庫名
        'database'        => '****',
        // 使用者名稱
        'username'        => 'sa',
        // 密碼
        'password'        => 'root',
        // 埠
        'hostport'        => '1433',
    ],

\thinkphp\library\think\db\connector\Sqlsrv.php

$dsn = 'sqlsrv:Database=' . $config['database'] . ';Server=' . $config['hostname'];

改為:

$dsn = 'dblib:version=8.0;charset=utf8;dbname=' . $config['database'] . ';host=' . $config['hostname'];

\thinkphp\library\think\db\Query.php

新增方法:

public function execute_sp($sql, $bind = [])
    {
        return $this->connection->execute_sp($sql, $bind);
    }

\thinkphp\library\think\db\Connection.php

新增方法:

/**
     * 執行sqlserver sp語句
     */
    public function execute_sp($sql, $bind = [])
    {
        $this->initConnect(true);
        if (!$this->linkID) {
            return false;
        }

        //sqlserver 相關配置,沒找在RDS裡設定的地方。
        $str = "SET QUOTED_IDENTIFIER ON; SET ANSI_WARNINGS ON; SET ANSI_PADDING ON; SET ANSI_NULLS ON; SET CONCAT_NULL_YIELDS_NULL ON; SET NOCOUNT ON;";
        $sql = $str . $sql;

        // 記錄SQL語句
        $this->queryStr = $sql;
        if ($bind) {
            $this->bind = $bind;
        }

        //釋放前次的查詢結果
        if (!empty($this->PDOStatement) && $this->PDOStatement->queryString != $sql) {
            $this->free();
        }

        Db::$executeTimes++;
        try {

            $this->PDOStatement = $this->linkID->prepare($sql);
            $this->bindParam($bind);

            // 執行語句
            $this->PDOStatement->execute();
            $this->PDOStatement->nextRowset();

            // 返回結果集
            return $this->getResult(false, true);
        } catch (\PDOException $e) {
            if ($this->isBreak($e)) {
                return $this->close()->execute($sql, $bind);
            }
            throw new PDOException($e, $this->config, $this->getLastsql());
        } catch (\Exception $e) {
            if ($this->isBreak($e)) {
                return $this->close()->execute($sql, $bind);
            }
            throw $e;
        }
    }

自己找個地方隨便測試一下

public function test()
    {
        $sql = "sp語句";
        $res = db2()->execute_sp($sql);
        print_r($res);
    }