언어
Microsoft. Data.SqlClient는 런타임 통계를 지원합니다. 유효한 True 개체의 SqlConnection 속성을 StatisticsEnabled(으)로 설정하여 통계를 사용하도록 설정합니다.
통계를 사용하도록 설정한 후 지정 시점의 스냅샷을 RetrieveStatistics 개체에서 가져오려면 IDictionary를 호출합니다. 순서가 지정되지 않은 이름/값 쌍을 열거하여 카운터를 읽습니다. 카운터를 다시 설정하려면 ResetStatistics를 호출합니다.
통계를 사용하도록 설정하지 않은 경우 예외 없이 각 카운터의 초기 값을 반환합니다 RetrieveStatistics . 통계를 사용하지 않도록 설정하면 카운터는 해당 지점까지 수집된 값을 유지합니다.
모든 통계 값은 각 연결 단위로 수집됩니다.
사용 가능한 통계 값
Microsoft SQL Server 공급자는 18개의 통계 값을 노출합니다. 사전의 Count 속성을 읽어 사용 가능한 항목 수를 가져옵니다. 모든 카운터는 Long을 사용하며, 이는 C#에서는 long, Visual Basic에서는 Int64라고 하는 64비트 형식입니다.
최대값은 Int64.MaxValue(2^63)-1입니다. 그 한도에 도달하면 카운터는 더 이상 정확하지 않습니다. 따라서 통계에 대해 유효한 최댓값은 Int64.MaxValue - 1, 또는 (2^63)-2입니다.
참고
나중에 반환된 통계의 수, 이름 및 순서가 변경될 수 있으므로 공급자 통계를 반환하는 데 사전을 사용합니다. 애플리케이션에서는 사전에서 특정 값이 발견될 것이라고 가정하지 말고, 대신 값이 존재하는지를 확인한 후에 적절히 분기해야 합니다.
다음 표에서는 사용할 수 있는 통계 값에 대해 설명합니다. 개별 값의 키 이름은 .NET Framework의 국가별 버전에서 지역화되어 있지 않습니다.
| 키 이름 | 설명 |
|---|---|
BuffersReceived |
애플리케이션에서 공급자 사용을 시작하고 통계를 활성화한 후 SQL Server에서 공급자가 받은 TDS(Tabular Data Stream) 패킷의 수를 반환합니다. |
BuffersSent |
통계를 사용하도록 설정한 후 공급자가 SQL Server에 보낸 TDS 패킷 수를 반환합니다. 긴 명령의 경우 버퍼가 여러 개 필요할 수 있습니다. 예를 들어, 긴 명령이 서버로 전송되고 6개의 패킷이 필요한 경우 ServerRoundtrips는 1개씩 증가하며 BuffersSent는 6개씩 증가합니다. |
BytesReceived |
애플리케이션에서 공급자 사용을 시작하고 통계를 활성화한 후 SQL Server에서 공급자가 받은 TDS 패킷의 데이터 바이트 수를 반환합니다. |
BytesSent |
애플리케이션에서 공급자 사용을 시작하고 통계를 사용하도록 설정한 후 SQL Server로 보낸 TDS 패킷의 데이터 바이트 수를 반환합니다. |
ConnectionTime |
통계가 활성화된 후 연결이 열려 있던 시간(밀리초)입니다(연결을 열기 전에 통계를 활성화한 경우에는 총 연결 시간). |
CursorOpens |
애플리케이션에서 공급자 사용을 시작하고 통계를 활성화한 후 연결을 통해 커서가 열린 횟수를 반환합니다. 읽기 전용/정방향 전용 결과가 SELECT 문에서 반환되더라도 커서로 간주되지 않으므로 이 카운터에 영향을 미치지 않습니다. |
ExecutionTime |
통계가 활성화된 후 서버의 응답을 기다린 시간과 공급자 자체에서 코드를 실행하는 데 걸린 시간을 포함하여 공급자에서 처리에 소요된 누적 시간(밀리초)을 반환합니다. 타이밍 코드를 포함하는 클래스는 다음과 같습니다. SqlConnectionSqlCommandSqlDataReaderSqlDataAdapterSqlTransactionSqlCommandBuilder성능이 중요한 멤버를 최대한 작게 유지하기 위해, 다음 멤버는 시간 측정되지 않습니다. SqlDataReaderthis[] 연산자(모든 오버로드)GetBooleanGetCharGetDateTimeGetDecimalGetDoubleGetFloatGetGuidGetInt16GetInt32GetInt64GetNameGetOrdinalGetSqlBinaryGetSqlBooleanGetSqlByteGetSqlDateTimeGetSqlDecimalGetSqlDoubleGetSqlGuidGetSqlInt16GetSqlInt32GetSqlInt64GetSqlMoneyGetSqlSingleGetSqlStringGetStringIsDBNull |
IduCount |
애플리케이션이 공급자를 사용하기 시작하고 통계를 사용하도록 설정한 후 연결을 통해 실행된 INSERT, DELETE, UPDATE 문의 총 개수를 반환합니다. |
IduRows |
애플리케이션이 공급자를 사용하기 시작하고 통계를 사용하도록 설정한 후, 연결을 통해 실행된 INSERT, DELETE, UPDATE 문이 영향을 미친 총 행 수를 반환합니다. |
NetworkServerTime |
애플리케이션에서 공급자 사용을 시작하고 통계를 활성화한 후 공급자에서 서버의 응답을 기다리는 데 소요된 누적 시간(밀리초 단위)의 양을 반환합니다. |
PreparedExecs |
애플리케이션에서 공급자 사용을 시작하고 통계를 활성화한 후 연결을 통해 실행되는 준비된 명령 수를 반환합니다. |
Prepares |
애플리케이션에서 공급자 사용을 시작하고 통계를 활성화한 후 연결을 통해 준비된 문 수를 반환합니다. |
SelectCount |
애플리케이션에서 통계를 사용하도록 설정한 후 연결을 통해 실행된 명령문 수를 SELECT 반환합니다. 커서에서 행을 검색하는 문을 포함합니다 FETCH .
SELECT 문의 경우 공급자는 SqlDataReader 결과의 끝에 도달하면 개수를 업데이트합니다. |
SelectRows |
애플리케이션에서 공급자 사용을 시작하고 통계를 활성화한 후 선택된 행 수를 반환합니다. 이 카운터는 호출자가 실제로 사용하지 않은 행을 포함하여 SQL 문에서 생성된 모든 행을 반영합니다. 예를 들어, 전체 결과 집합을 읽기 전에 데이터 판독기를 닫으면 개수가 달라지지 않습니다. 여기에는 커서에서 FETCH 문을 통해 검색된 행이 포함됩니다. |
ServerRoundtrips |
애플리케이션에서 공급자 사용을 시작하고 통계를 활성화한 후 연결에서 서버로 명령을 보내고 응답을 받은 횟수를 반환합니다. |
SumResultSets |
애플리케이션에서 공급자 사용을 시작하고 통계를 활성화한 후 사용된 결과 집합의 수를 반환합니다. 예를 들어, 여기에는 클라이언트로 반환된 모든 결과 집합이 포함됩니다. 커서의 경우 각 반입 또는 블록 반입 작업은 개별 결과 집합으로 간주됩니다. |
Transactions |
애플리케이션에서 공급자 사용을 시작하고 통계를 사용하도록 설정한 후, 롤백을 포함하여 시작된 사용자 트랜잭션의 수를 반환합니다. 자동 커밋 기능이 작동되는 상태에서 연결을 실행하면 각 명령은 트랜잭션으로 간주됩니다. 이 카운터는 트랜잭션이 나중에 커밋되거나 롤백되는지 여부와 관계없이 BEGIN TRAN 문이 실행되는 즉시 트랜잭션 수를 증분합니다. |
UnpreparedExecs |
애플리케이션에서 공급자 사용을 시작하고 통계를 활성화한 후 실행된 준비되지 않은 문의 수를 반환합니다. |
값 가져오기
다음 콘솔 애플리케이션에서는 연결에서 통계를 활성화하고 네 가지 개별 통계 값을 검색하여 콘솔 창에 쓰는 방법을 보여 줍니다.
참고
다음 예제에서는 SQL Server에 포함된 샘플 AdventureWorks 데이터베이스를 사용합니다. 샘플 코드에 제공된 연결 문자열은 데이터베이스가 로컬 컴퓨터에 설치되어 있고 사용 가능한 것으로 가정합니다. 사용자 환경에 필요한 경우 연결 문자열을 수정합니다.
Option Strict On
Imports System
Imports System.Collections
Imports System.Data
Imports Microsoft.Data.SqlClient
Module Module1
Sub Main()
Dim connectionString As String = GetConnectionString()
Using awConnection As New SqlConnection(connectionString)
' StatisticsEnabled is False by default.
' It must be set to True to start the
' statistic collection process.
awConnection.StatisticsEnabled = True
Dim productSQL As String = "SELECT * FROM Production.Product"
Dim productAdapter As _
New SqlDataAdapter(productSQL, awConnection)
Dim awDataSet As New DataSet()
awConnection.Open()
productAdapter.Fill(awDataSet, "ProductTable")
' Retrieve the current statistics as
' a collection of values at this point
' and time.
Dim currentStatistics As IDictionary = _
awConnection.RetrieveStatistics()
Console.WriteLine("Total Counters: " & _
currentStatistics.Count.ToString())
Console.WriteLine()
' Retrieve a few individual values
' related to the previous command.
Dim bytesReceived As Long = _
CLng(currentStatistics.Item("BytesReceived"))
Dim bytesSent As Long = _
CLng(currentStatistics.Item("BytesSent"))
Dim selectCount As Long = _
CLng(currentStatistics.Item("SelectCount"))
Dim selectRows As Long = _
CLng(currentStatistics.Item("SelectRows"))
Console.WriteLine("BytesReceived: " & bytesReceived.ToString())
Console.WriteLine("BytesSent: " & bytesSent.ToString())
Console.WriteLine("SelectCount: " & selectCount.ToString())
Console.WriteLine("SelectRows: " & selectRows.ToString())
Console.WriteLine()
Console.WriteLine("Press any key to continue")
Console.ReadLine()
End Using
End Sub
Function GetConnectionString() As String
' To avoid storing the connection string in your code,
' you can retrieve it from a configuration file.
Return "..."
End Function
End Module
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;
namespace CS_Stats_Console_GetValue
{
class Program
{
static void Main(string[] args)
{
string connectionString = GetConnectionString();
using (SqlConnection awConnection =
new SqlConnection(connectionString))
{
// StatisticsEnabled is False by default.
// It must be set to True to start the
// statistic collection process.
awConnection.StatisticsEnabled = true;
string productSQL = "SELECT * FROM Production.Product";
SqlDataAdapter productAdapter =
new SqlDataAdapter(productSQL, awConnection);
DataSet awDataSet = new DataSet();
awConnection.Open();
productAdapter.Fill(awDataSet, "ProductTable");
// Retrieve the current statistics as
// a collection of values at this point
// and time.
IDictionary currentStatistics =
awConnection.RetrieveStatistics();
Console.WriteLine("Total Counters: " +
currentStatistics.Count.ToString());
Console.WriteLine();
// Retrieve a few individual values
// related to the previous command.
long bytesReceived =
(long) currentStatistics["BytesReceived"];
long bytesSent =
(long) currentStatistics["BytesSent"];
long selectCount =
(long) currentStatistics["SelectCount"];
long selectRows =
(long) currentStatistics["SelectRows"];
Console.WriteLine("BytesReceived: " +
bytesReceived.ToString());
Console.WriteLine("BytesSent: " +
bytesSent.ToString());
Console.WriteLine("SelectCount: " +
selectCount.ToString());
Console.WriteLine("SelectRows: " +
selectRows.ToString());
Console.WriteLine();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
}
private static string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "...";
}
}
}
모든 값 검색
다음 콘솔 애플리케이션에서는 연결에서 통계를 활성화하고 열거자를 사용하여 모든 사용 가능한 통계 값을 검색한 후 콘솔 창에 쓰는 방법을 보여 줍니다.
참고
다음 예제에서는 SQL Server에 포함된 샘플 AdventureWorks 데이터베이스를 사용합니다. 샘플 코드에 제공된 연결 문자열은 데이터베이스가 로컬 컴퓨터에 설치되어 있고 사용 가능한 것으로 가정합니다. 사용자 환경에 필요한 경우 연결 문자열을 수정합니다.
Option Strict On
Imports System
Imports System.Collections
Imports System.Data
Imports Microsoft.Data.SqlClient
Module Module1
Sub Main()
Dim connectionString As String = GetConnectionString()
Using awConnection As New SqlConnection(connectionString)
' StatisticsEnabled is False by default.
' It must be set to True to start the
' statistic collection process.
awConnection.StatisticsEnabled = True
Dim productSQL As String = "SELECT * FROM Production.Product"
Dim productAdapter As _
New SqlDataAdapter(productSQL, awConnection)
Dim awDataSet As New DataSet()
awConnection.Open()
productAdapter.Fill(awDataSet, "ProductTable")
' Retrieve the current statistics as
' a collection of values at this point
' and time.
Dim currentStatistics As IDictionary = _
awConnection.RetrieveStatistics()
Console.WriteLine("Total Counters: " & _
currentStatistics.Count.ToString())
Console.WriteLine()
Console.WriteLine("Key Name and Value")
' Note the entries are unsorted.
For Each entry As DictionaryEntry In currentStatistics
Console.WriteLine(entry.Key.ToString() & _
": " & entry.Value.ToString())
Next
Console.WriteLine()
Console.WriteLine("Press any key to continue")
Console.ReadLine()
End Using
End Sub
Function GetConnectionString() As String
' To avoid storing the connection string in your code,
' you can retrieve it from a configuration file.
Return "..."
End Function
End Module
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Microsoft.Data.SqlClient;
namespace CS_Stats_Console_GetAll
{
class Program
{
static void Main(string[] args)
{
string connectionString = GetConnectionString();
using (SqlConnection awConnection =
new SqlConnection(connectionString))
{
// StatisticsEnabled is False by default.
// It must be set to True to start the
// statistic collection process.
awConnection.StatisticsEnabled = true;
string productSQL = "SELECT * FROM Production.Product";
SqlDataAdapter productAdapter =
new SqlDataAdapter(productSQL, awConnection);
DataSet awDataSet = new DataSet();
awConnection.Open();
productAdapter.Fill(awDataSet, "ProductTable");
// Retrieve the current statistics as
// a collection of values at this point
// and time.
IDictionary currentStatistics =
awConnection.RetrieveStatistics();
Console.WriteLine("Total Counters: " +
currentStatistics.Count.ToString());
Console.WriteLine();
Console.WriteLine("Key Name and Value");
// Note the entries are unsorted.
foreach (DictionaryEntry entry in currentStatistics)
{
Console.WriteLine(entry.Key.ToString() +
": " + entry.Value.ToString());
}
Console.WriteLine();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
}
private static string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "...";
}
}
}