关于php连接mssql:pdo odbc sql server

关于Php连接MSSQL,我们可以使用PDO、ODBC和SQL Server三种方式,下面分别详细介绍。

1. 使用PDO连接MSSQL

安装PDO和pdo_sqlsrv驱动

使用PDO连接MSSQL需要安装PDO和pdo_sqlsrv驱动,可以通过以下命令安装:

sudo apt-get install php7.0-pdo
sudo apt-get install php7.0-sqlsrv

连接MSSQL服务器

try {
    $server_name = "localhost";
    $database_name = "test_db";
    $username = "sa";
    $password = "sa123456";
    $pdo = new PDO("sqlsrv:Server=$server_name;Database=$database_name", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully!\n";
} catch (PDOException $e) {
    echo "Failed to connect to MSSQL: " . $e->getMessage();
}

2. 使用ODBC连接MSSQL

安装odbc和odbc驱动

使用ODBC连接MSSQL需要安装odbc和odbc驱动,可以通过以下命令安装:

sudo apt-get install unixodbc-dev
sudo pecl install pdo_odbc

连接MSSQL服务器

try {
    $server_name = "localhost";
    $database_name = "test_db";
    $username = "sa";
    $password = "sa123456";
    $dsn = "odbc:Driver={SQL Server};Server=$server_name;Database=$database_name";
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully!\n";
} catch (PDOException $e) {
    echo "Failed to connect to MSSQL: " . $e->getMessage();
}

3. 使用SQL Server连接MSSQL

安装sqlsrv

使用SQL Server连接MSSQL需要安装sqlsrv,可以通过以下命令安装:

sudo apt-get install php7.0-sqlsrv

连接MSSQL服务器

try {
    $server_name = "localhost";
    $database_name = "test_db";
    $username = "sa";
    $password = "sa123456";
    $connection_info = array( "Database"=>$database_name, "UID"=>$username, "PWD"=>$password);
    $conn = sqlsrv_connect( $server_name, $connection_info );
    if( $conn ) {
        echo "Connected successfully!\n";
    } else {
        echo "Failed to connect to MSSQL\n";
        die( print_r( sqlsrv_errors(), true));
    }
} catch (PDOException $e) {
    echo "Failed to connect to MSSQL: " . $e->getMessage();
}

以上就是连接MSSQL的三种方式,分别使用PDO、ODBC和SQL Server。根据不同的需求选择不同的方式来连接MSSQL。

营销型网站