mangalam
mangalam

Reputation: 21

how to use only single connection to execute multiple queries in Npgsql?

I have created multiple connections in npgsql to execute multiple queries as shown below code.

    class TransactionAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
    public static void GetTransactions()
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            var transactions = connection.Query<TransactionView>(@"SELECT t.transaction_id,t.account_id,a.account_name, a.type,t.note, t.amount, t.date
                                                               FROM account AS a
                                                               INNER JOIN transaction AS t ON a.account_id = t.account_id");
            transactions.Dump();
        }
    }

    public static void GetTransactionInfo(int id)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            var transactionInfo = connection.Query<TransactionView>(@"SELECT a.account_name, a.type, DATE(t.date), t.amount, t.note, t.transaction_id 
                                                                  FROM transaction AS t 
                                                                  INNER JOIN account AS a ON t.account_id = a.account_id 
                                                                  WHERE t.transaction_id = @id", new { id });
            transactionInfo.Dump();
        }
    }

    public static void MakeTransaction(Transaction transaction, Account account)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            connection.Execute(@"INSERT INTO transaction(account_id,amount,date,note)
                                         SELECT a.account_id,@amount, @date, @note
                                         FROM account AS a
                                         WHERE a.account_name=@account_name", new { transaction.Amount, transaction.Date, transaction.Note, account.Account_Name });
        }
    }
}

I wanted to execute all queries with a single connection. How can I do that?

Upvotes: 2

Views: 2058

Answers (1)

ManojRawat
ManojRawat

Reputation: 81

Why cannot you use Batching as mentioned in Npgsql documentation.

await using var batch = new NpgsqlBatch(conn)
{
    BatchCommands =
    {
        new("INSERT INTO table (col1) VALUES ('foo')"),
        new("SELECT * FROM table")
    }
};

await using var reader = await batch.ExecuteReaderAsync();

Source : https://www.npgsql.org/doc/basic-usage.html

PS : Thought of commenting first, but cannot do it because of less reputation points :D

Upvotes: 4

Related Questions