4단계: PHP를 사용하여 탄력적으로 SQL에 연결

PHP 드라이버 다운로드

데모 프로그램은 연결 시도 중 일시적인 오류로 재시도하도록 디자인되었습니다. (일시적 오류 코드는 이 부록에 나열된 대로 접두사 '08'로 시작합니다.)그러나 쿼리 명령 중 일시적인 오류로 인해 쿼리 명령을 다시 시도하기 이전에 프로그램이 연결을 카드 연결을 해제하고 새 연결을 생성합니다. 이 디자인 선택에 대해서는 권장하거나 만류하지는 않습니다. 데모 프로그램은 사용자가 사용할 수 있는 몇 가지 디자인의 유연성을 보여 줍니다.

이 코드 샘플의 길이는 주로 catch 예외 논리로 인해 발생합니다.

sqlsrv_query() 함수를 사용하여 SQL Database에 대한 쿼리에서 결과 집합을 검색할 수 있습니다. 이 함수는 본질적으로 모든 쿼리 및 연결 개체를 허용하며, sqlsrv_fetch_array()을 사용하여 반복될 수 있는 결과 집합을 반환합니다.


    <?php
        // Variables to tune the retry logic.
        $connectionTimeoutSeconds = 30;  // Default of 15 seconds is too short over the Internet, sometimes.
        $maxCountTriesConnectAndQuery = 3;  // You can adjust the various retry count values.
        $secondsBetweenRetries = 4;  // Simple retry strategy.
        $errNo = 0;
        $serverName = "tcp:yourdatabase.database.windows.net,1433";
        $connectionOptions = array("Database"=>"AdventureWorks",
           "Uid"=>"yourusername", "PWD"=>"yourpassword", "LoginTimeout" => $connectionTimeoutSeconds);
        $conn = null;
        $arrayOfTransientErrors = array('08001', '08002', '08003', '08004', '08007', '08S01');
        for ($cc = 1; $cc <= $maxCountTriesConnectAndQuery; $cc++) {
            // [A.2] Connect, which proceeds to issue a query command.
            $conn = sqlsrv_connect($serverName, $connectionOptions);
            if ($conn === true) {
                echo "Connection was established";
                echo "<br>";

                $tsql = "SELECT Name FROM Production.ProductCategory";
                $stmt = sqlsrv_query($conn, $tsql);
                if ($stmt === false) {
                    echo "Error in query execution";
                    echo "<br>";
                    die(print_r(sqlsrv_errors(), true));
                }
                while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                    echo $row['Name'] . "<br/>" ;
                }
                sqlsrv_free_stmt($stmt);
                sqlsrv_close( $conn);
                break;
            } else {
                // [A.4] Check whether the error code is on the list of allowed transients.
                $isTransientError = false;
                $errorCode = '';
                if (($errors = sqlsrv_errors()) != null) {
                    foreach ($errors as $error) {
                        $errorCode = $error['code'];
                        $isTransientError = in_array($errorCode, $arrayOfTransientErrors);
                        if ($isTransientError) {
                            break;
                        }
                    }
                }
                if (!$isTransientError) {
                    // it is a static persistent error...
                    echo("Persistent error suffered with error code = $errorCode. Program will terminate.");
                    echo "<br>";
                    // [A.5] Either the connection attempt or the query command attempt suffered a persistent error condition.
                    // Break the loop, let the hopeless program end.
                    exit(0);
                }
                // [A.6] It is a transient error from an attempt to issue a query command.
                // So let this method reloop and try again. However, we recommend that the new query
                // attempt should start at the beginning and establish a new connection.
                if ($cc >= $maxCountTriesConnectAndQuery) {
                    echo "Transient errors suffered in too many retries - $cc. Program will terminate.";
                    echo "<br>";
                    exit(0);
                }
                echo("Transient error encountered with error code = $errorCode. Program might retry by itself.");
                echo "<br>";
                echo "$cc attempts so far. Might retry.";
                echo "<br>";
                // A very simple retry strategy, a brief pause before looping.
                sleep(1*$secondsBetweenRetries);
            }
            // [A.3] All has gone well, so let the program end.
        }
    ?>