SQL문을 비동기적으로 실행
Command 객체에는 Connection 객체에서 비동기적으로 데이터베이스에 연결하는 OpenAsync()처럼 SQL문도 비동기적으로 실행할 수 있는 함수들이 준비되어 있습니다.
이런 비동기 메서드들을 사용하면 애플리케이션의 응답성을 유지하면서 데이터베이스 작업을 수행할 수 있습니다.
예를 들어, ExecuteScalarAsync()
는 비동기적으로 단일 값을 반환하는 SQL 명령문을 실행하는 메서드입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public async Task<int> GetRecordCountAsync(string connectionString, string tableName)
{
using (var connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
using (var command = new SqlCommand($"SELECT COUNT(*) FROM {tableName}", connection))
{
// ExecuteScalarAsync는 object를 반환하므로, int로 캐스팅합니다.
int count = (int)await command.ExecuteScalarAsync();
return count;
}
}
}
- SqlConnection.OpenAsync()
- 데이터베이스 연결을 비동기적으로 엽니다.
- SqlCommand.ExecuteScalarAsync()
- SQL 쿼리를 비동기적으로 실행하여 단일 값을 반환합니다. 이때,
object
타입으로 반환되며, 필요한 경우 적절한 타입으로 캐스팅해야 합니다.
- SQL 쿼리를 비동기적으로 실행하여 단일 값을 반환합니다. 이때,
다른 비동기 메서드들
그 외에 ADO.NET에는 다양한 비동기 메서드들이 존재합니다. 아래 예제는 주로 사용될지도 모르는 주요 메서드들 두 개를 가져와 봤습니다.
다른 메서드들은 intellisense의 설명이나 공식 문서를 참조해 주세요.
ExecuteNonQueryAsync()
이 메서드는 데이터베이스에 명령문을 실행하고, 영향을 받은 행의 수를 반환합니다. INSERT, UPDATE, DELETE 명령문에 주로 사용됩니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public async Task<int> UpdateRecordAsync(string connectionString, string tableName, int id, string newValue)
{
using (var connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
string query = $"UPDATE {tableName} SET ColumnName = @NewValue WHERE Id = @Id";
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@NewValue", newValue);
command.Parameters.AddWithValue("@Id", id);
int rowsAffected = await command.ExecuteNonQueryAsync();
return rowsAffected;
}
}
}
ExecuteReaderAsync()
이 메서드는 SQL 쿼리를 실행하고 결과 집합을 읽기 위한 SqlDataReader
객체를 반환합니다. SELECT 문에 주로 사용됩니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public async Task<List<string>> GetColumnValuesAsync(string connectionString, string tableName)
{
var results = new List<string>();
using (var connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
string query = $"SELECT ColumnName FROM {tableName}";
using (var command = new SqlCommand(query, connection))
{
using (var reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
results.Add(reader.GetString(0));
}
}
}
}
return results;
}
참고
이 기사는 저작권자의 CC BY-NC-ND 4.0 라이센스를 따릅니다.