.Net CoreNpgsqlプリペアドステートメント

Sep 09 2020

プリペアドステートメントを使用して、.Net Coreアプリの一部のSQLステートメントをより再利用できるように変更しようとしていますが、NpgsqlDbTypeで問題が発生しています。

ドキュメントの指示に従おうとしました。

NpgsqlCommand command = new NpgsqlCommand (
    " select * from computers where com_phys = @com_phys ",
    dbconnection
);
command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
command.Prepare();

しかし、それはコンパイルに失敗している、と言っています

The name 'NpgsqlDbType' does not exist in the current context

私は何かが足りないのですか?NpgsqlDbTypeを使用するにはどうすればよいですか?

更新

それが他の誰かに利益をもたらすことができる場合に備えて、私はここに最終的な作業を置いています

// prepare

NpgsqlCommand command = new NpgsqlCommand (
    " select * from computers where com_phys = @com_phys ",
    dbconnection
);
var param01 = command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
command.Prepare();

// execute 01

param01.Value = "value01";
var results = command.ExecuteReader();
while(results.Read()) {
   // nothing
}
command.Close();

// execute 02

param01.Value = "value02";
var results = command.ExecuteReader();
while(results.Read()) {
   // nothing
}
command.Close();

回答

2 ESG Sep 09 2020 at 02:16

NpgsqlDbTypeは、NpgsqlTypes名前空間にあります。上部にNpgsqlTypesを使用していることを確認してください。

同時に値を設定したい場合は、のAddWithValue代わりにを使用してくださいAdd

NpgsqlCommand command = new NpgsqlCommand (
    " select * from computers where com_phys = @com_phys ",
    dbconnection
);
command.Parameters.AddValue("com_phys", NpgsqlDbType.Varchar, value);
// OR command.Parameters.AddValue("com_phys", NpgsqlDbType.Varchar, size, value);
// OR command.Parameters.AddValue("com_phys", value);
command.Prepare();

パラメータを1回追加して複数回実行する場合は、パラメータへの参照を保持できます

var parameter = command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);

// Later, in a loop
parameter.Value = "someValue";