postgresql 如何在Npgsql中使用单个连接执行多个查询?

x3naxklr  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(117)

我在npgsql中创建了多个连接来执行多个查询,如下面的代码所示。

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 });
        }
    }
}

字符串
我想用一个连接执行所有查询。我该怎么做?

xhv8bpkk

xhv8bpkk1#

为什么不能使用Npgsql文档中提到的Batching

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();

字符串
来源:https://www.npgsql.org/doc/basic-usage.html
PS:本来想先评论的,但是因为声望点少,所以不能评论:D

相关问题