jsm.database 1.0.2

dotnet add package jsm.database --version 1.0.2
                    
NuGet\Install-Package jsm.database -Version 1.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="jsm.database" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="jsm.database" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="jsm.database" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add jsm.database --version 1.0.2
                    
#r "nuget: jsm.database, 1.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package jsm.database@1.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=jsm.database&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=jsm.database&version=1.0.2
                    
Install as a Cake Tool

jsm.database

MySQL 및 PostgreSQL 데이터베이스 관리를 위한 .NET Standard 2.0 기반 라이브러리입니다. 간편한 API로 데이터베이스 연결, 쿼리 실행, 트랜잭션 관리를 제공합니다.

주요 기능

🗄️ 데이터베이스 지원

  • MySQL: MySqlConnector를 사용한 안정적인 MySQL 연결
  • PostgreSQL: Npgsql을 사용한 PostgreSQL 연결
  • 통합 API: 동일한 인터페이스로 두 데이터베이스 모두 사용 가능

🔌 연결 관리

  • 자동 연결 문자열 생성: 호스트, 데이터베이스, 사용자 정보만 제공하면 자동으로 연결 문자열 생성
  • 연결 상태 관리: 연결 상태 확인 및 자동 재연결
  • 리소스 관리: IDisposable 패턴으로 안전한 리소스 해제

📊 쿼리 실행

  • SELECT 쿼리: ExecuteQueryAsync - 결과를 Dictionary 리스트로 반환
  • INSERT/UPDATE/DELETE: ExecuteNonQueryAsync - 영향받은 행 수 반환
  • 스칼라 쿼리: ExecuteScalarAsync - 단일 값 반환 (COUNT, MAX 등)
  • 파라미터화된 쿼리: SQL Injection 방지를 위한 파라미터 지원

🔄 트랜잭션 지원

  • 트랜잭션 시작: BeginTransactionAsync
  • 커밋: CommitTransactionAsync
  • 롤백: RollbackTransactionAsync

설치

.NET CLI

dotnet add package jsm.database

Package Manager Console

Install-Package jsm.database

PackageReference

<ItemGroup>
  <PackageReference Include="jsm.database" Version="1.0.0" />
</ItemGroup>

빠른 시작

MySQL 사용 예제

using jsm.database;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

// DatabaseClient 생성 (개별 파라미터 사용)
using (var client = new DatabaseClient(
    DatabaseType.MySql,
    host: "localhost",
    database: "mydb",
    userId: "root",
    password: "password",
    port: 3306))
{
    // 연결
    await client.ConnectAsync();
    Console.WriteLine("MySQL 연결 성공");

    // SELECT 쿼리 실행
    var results = await client.ExecuteQueryAsync(
        "SELECT * FROM users WHERE age > @age",
        new Dictionary<string, object> { { "age", 18 } }
    );

    foreach (var row in results)
    {
        Console.WriteLine($"Name: {row["name"]}, Age: {row["age"]}");
    }

    // INSERT 쿼리 실행
    var affectedRows = await client.ExecuteNonQueryAsync(
        "INSERT INTO users (name, age) VALUES (@name, @age)",
        new Dictionary<string, object> { { "name", "John" }, { "age", 25 } }
    );
    Console.WriteLine($"영향받은 행 수: {affectedRows}");

    // 스칼라 쿼리 실행
    var count = await client.ExecuteScalarAsync(
        "SELECT COUNT(*) FROM users"
    );
    Console.WriteLine($"총 사용자 수: {count}");
}

PostgreSQL 사용 예제

using jsm.database;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

// DatabaseClient 생성 (포트 생략 시 기본값 5432 사용)
using (var client = new DatabaseClient(
    DatabaseType.PostgreSQL,
    host: "localhost",
    database: "mydb",
    userId: "postgres",
    password: "password"))
{
    // 연결
    await client.ConnectAsync();
    Console.WriteLine("PostgreSQL 연결 성공");

    // SELECT 쿼리 실행
    var results = await client.ExecuteQueryAsync(
        "SELECT * FROM users WHERE age > @age",
        new Dictionary<string, object> { { "age", 18 } }
    );

    foreach (var row in results)
    {
        Console.WriteLine($"Name: {row["name"]}, Age: {row["age"]}");
    }
}

트랜잭션 사용 예제

트랜잭션은 **원자성(Atomicity)**을 보장합니다. 모든 작업이 성공하거나 모두 롤백됩니다.

은행 송금 예시:

using (var client = new DatabaseClient(
    DatabaseType.MySql,
    host: "localhost",
    database: "bank",
    userId: "root",
    password: "password"))
{
    await client.ConnectAsync();

    try
    {
        // 트랜잭션 시작
        await client.BeginTransactionAsync();

        // 1. 송금자 계좌에서 돈 차감
        await client.ExecuteNonQueryAsync(
            "UPDATE accounts SET balance = balance - @amount WHERE account_id = @from",
            new Dictionary<string, object> { { "amount", 10000 }, { "from", "A001" } }
        );

        // 2. 수신자 계좌에 돈 추가
        await client.ExecuteNonQueryAsync(
            "UPDATE accounts SET balance = balance + @amount WHERE account_id = @to",
            new Dictionary<string, object> { { "amount", 10000 }, { "to", "B002" } }
        );

        // 모든 작업이 성공하면 커밋 (두 작업 모두 적용됨)
        await client.CommitTransactionAsync();
        Console.WriteLine("송금 성공: 10,000원 이체 완료");
    }
    catch (Exception ex)
    {
        // 하나라도 실패하면 롤백 (두 작업 모두 취소됨)
        await client.RollbackTransactionAsync();
        Console.WriteLine($"송금 실패: 모든 작업이 취소되었습니다. {ex.Message}");
    }
}

일반적인 트랜잭션 패턴:

using (var client = new DatabaseClient(
    DatabaseType.MySql,
    host: "localhost",
    database: "mydb",
    userId: "root",
    password: "password"))
{
    await client.ConnectAsync();

    try
    {
        // 트랜잭션 시작
        await client.BeginTransactionAsync();

        // 여러 쿼리 실행
        await client.ExecuteNonQueryAsync(
            "UPDATE users SET age = @age WHERE id = @id",
            new Dictionary<string, object> { { "age", 30 }, { "id", 1 } }
        );

        await client.ExecuteNonQueryAsync(
            "INSERT INTO logs (message) VALUES (@message)",
            new Dictionary<string, object> { { "message", "User updated" } }
        );

        // 모든 작업이 성공하면 커밋
        await client.CommitTransactionAsync();
        Console.WriteLine("트랜잭션 커밋 성공");
    }
    catch (Exception ex)
    {
        // 하나라도 실패하면 롤백 (모든 작업 취소)
        await client.RollbackTransactionAsync();
        Console.WriteLine($"트랜잭션 롤백: {ex.Message}");
    }
}

트랜잭션의 특징:

  • 원자성: 모든 작업이 성공하거나 모두 롤백 (All or Nothing)
  • 일관성: 데이터베이스 상태가 항상 일관되게 유지
  • 격리성: 다른 트랜잭션과 격리되어 실행
  • 지속성: 커밋된 변경사항은 영구적으로 저장

주요 클래스

DatabaseClient

데이터베이스 클라이언트의 메인 클래스입니다. 생성자에서 DB 타입을 지정하면 해당 DB의 기능을 수행합니다.

생성자:

public DatabaseClient(
    DatabaseType databaseType,
    string host,
    string database,
    string userId,
    string password,
    int? port = null)

주요 메서드:

  • ConnectAsync() - 데이터베이스 연결
  • DisconnectAsync() - 데이터베이스 연결 종료
  • ExecuteQueryAsync(string query, Dictionary<string, object> parameters = null) - SELECT 쿼리 실행
  • ExecuteNonQueryAsync(string query, Dictionary<string, object> parameters = null) - INSERT/UPDATE/DELETE 실행
  • ExecuteScalarAsync(string query, Dictionary<string, object> parameters = null) - 스칼라 값 반환
  • BeginTransactionAsync() - 트랜잭션 시작
  • CommitTransactionAsync() - 트랜잭션 커밋
  • RollbackTransactionAsync() - 트랜잭션 롤백

DatabaseType

지원하는 데이터베이스 타입을 나타내는 열거형입니다.

public enum DatabaseType
{
    MySql,      // MySQL 데이터베이스
    PostgreSQL  // PostgreSQL 데이터베이스
}

DatabaseException

데이터베이스 작업 중 발생한 예외입니다.

public class DatabaseException : Exception
{
    public DatabaseType DatabaseType { get; }
    public string SqlQuery { get; }
}

파라미터화된 쿼리

SQL Injection을 방지하기 위해 파라미터화된 쿼리를 사용하세요. 파라미터 키는 @ 접두사 없이 입력하면 됩니다.

// 올바른 사용법
var results = await client.ExecuteQueryAsync(
    "SELECT * FROM users WHERE name = @name AND age > @age",
    new Dictionary<string, object> 
    { 
        { "name", "John" }, 
        { "age", 18 } 
    }
);

// 잘못된 사용법 (SQL Injection 위험)
var results = await client.ExecuteQueryAsync(
    $"SELECT * FROM users WHERE name = '{userInput}'"  // ❌ 위험!
);

포트 기본값

포트를 지정하지 않으면 다음 기본값이 사용됩니다:

  • MySQL: 3306
  • PostgreSQL: 5432
// 포트 생략 (기본값 사용)
var client = new DatabaseClient(
    DatabaseType.MySql,
    host: "localhost",
    database: "mydb",
    userId: "root",
    password: "password"
);

// 포트 지정
var client = new DatabaseClient(
    DatabaseType.MySql,
    host: "localhost",
    database: "mydb",
    userId: "root",
    password: "password",
    port: 3307  // 사용자 정의 포트
);

의존성

이 라이브러리는 다음 NuGet 패키지에 의존합니다:

  • MySqlConnector (2.3.7) - MySQL 연결용
  • Npgsql (8.0.5) - PostgreSQL 연결용

라이선스

MIT License

기여

버그 리포트나 기능 제안은 GitHub Issues를 통해 제출해주세요.

관련 프로젝트

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.2 292 11/13/2025