0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C# ASP.NET】PostgreSQLを使った生のINSERT文とDBへの実装方法

Posted at

「トラブルシューティング」

ここには書いていないが、SELECTしたあとに、つづけてINSERTしようとするとExecuteNonQuery間で戻り値が「-1」となって原因を確認すると下記が判明した。

★問題2:commandを再利用している

最初の SELECT 用に使った command インスタンスをそのまま INSERT に再利用していた。

クエリが INSERT に変わっているのに、command.CommandText を設定していない。

Parameters も以前の状態を引きずる可能性がある。

ExecuteNonQuery() は SELECT クエリに対しては常に -1 をへんきゃされていた。。

解決策:新しい NpgsqlCommand を作成

また、生のINSERT文を使って可読性を上げるために下記の通りクエリを修正した。

sample.cs
string insertQuery = @"
                    INSERT INTO ""Books""
                    (
                        ""Isbn"",
                        ""Title"",
                        ""Price"",
                        ""Publisher"",
                        ""Published"",
                        ""Sample""
                    )
                    VALUES
                    (
                        @BookIsbn,
                        @BookTitle,
                        @BookPrice,
                        @BookPublisher,
                        @BookPublished,
                        @BookSample
                    )";

全体コードは、下記の通り。

sample.cs
using (var transaction = connection.BeginTransaction())
{
    try
    {
        string insertQuery = $@"
            INSERT INTO ""Books""
            (
                ""Isbn"", 
                ""Title"", 
                ""Price"", 
                ""Publisher"", 
                ""Published"", 
                ""Sample""
            )
            VALUES 
            (
                @BookIsbn, 
                @BookTitle, 
                @BookPrice, 
                @BookPublisher, 
                @BookPublished, 
                @BookSample
            )";

        using (var insertCommand = new NpgsqlCommand(insertQuery, connection, transaction))
        {
            insertCommand.Parameters.AddWithValue("@BookIsbn", book.Isbn);
            insertCommand.Parameters.AddWithValue("@BookTitle", book.Title);
            insertCommand.Parameters.AddWithValue("@BookPrice", book.Price);
            insertCommand.Parameters.AddWithValue("@BookPublisher", book.Publisher);
            insertCommand.Parameters.AddWithValue("@BookPublished", book.Published ?? (object)DBNull.Value);
            insertCommand.Parameters.AddWithValue("@BookSample", book.Sample);

            int executeRow = await insertCommand.ExecuteNonQueryAsync();

            if (executeRow > 0)
            {
                transaction.Commit();
                return Json(new { status = 200, message = $"{executeRow}件の登録完了。" });
            }
            else
            {
                transaction.Rollback();
                return Json(new { status = 500, message = "データ挿入に失敗しました。" });
            }
        }
    }
    catch (Exception ex)
    {
        transaction.Rollback();
        return Json(new { status = 500, message = "エラー", error = ex.Message });
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?