0

I am trying to make laravel work with mssql and i always get this error:

"SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (192.168.1.1:1433) (severity 9) (SQL: SELECT GETDATE()) (View: /resources/views/teste.blade.php)"

but if i try a simple script:

<?php 
 try {
$hostname = "192.168.1.1";
$port = 1433;
$dbname = "some_db";
$username = "some_user";
$pw = "some_pass";

$dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }

$stmt = $dbh->prepare("select getdate()");

  $stmt->execute();


  while ($row = $stmt->fetch()) {
    print_r($row);
  }
  unset($dbh); unset($stmt);
?>

it works fine.... does laravel needs any special config or doesn't use pdo ?

1 Answers1

1

You might want to see which DSN type Laravel's SqlServerConnector class getDSN() method is returning.

It's located in: /vendor/laravel/framework/src/Illuminate/Database/Connectors/SqlServerConnector.php

In my case, I was using ODBC but the getDSN() method was returning the Dblib DSN by default. (ODBC and Dblib were both in the getAvailableDrivers() array but it checks for Dblib first.)

The SqlServerConnector class getDsn() method in laravel v5.6:

protected function getDsn(array $config)
{

   // checks for dblib first, by default. =(

    if (in_array('dblib', $this->getAvailableDrivers())) {
        return $this->getDblibDsn($config);
    } elseif ($this->prefersOdbc($config)) {
        return $this->getOdbcDsn($config);
    }

    return $this->getSqlSrvDsn($config);
}

UPDATE: I just noticed they reversed it in laravel v5.7:

protected function getDsn(array $config)
{

   // Checking for ODBC first, before DBlib!

    if ($this->prefersOdbc($config)) {
        return $this->getOdbcDsn($config);
    }

    if (in_array('sqlsrv', $this->getAvailableDrivers())) {
        return $this->getSqlSrvDsn($config);
    } else {
        return $this->getDblibDsn($config);
    }
}

Per this answer I ended up creating an overriding SqlServerConnector class and registered it in the AppServiceProvider, that checked for ODBC first.

ourmandave
  • 1,505
  • 2
  • 15
  • 49