问题
Is there a way to do bulk operations with npgsql like with ODP.NET array binding feature ? I am aware of the Batching/Pipelining/multiple SQL statements in a single command (executing in a single roundtrip) but as far as I understand you can't use it in the same way, with different parameters for every statement. If it can be done, I would be happy if someone could provide an example how to convert the code below to Npgsql.
List<dto> listDTO; // list containing up to 1000 dtos
OraCommand = db.GetOracleCommand();
OraCommand.CommandText = "INSERT INTO TABLE (ID, FIELD1, FIELD2) VALUES (:ID, :FIELD1, :FIELD2)";
object[] FIELD1 = new object[listDTO.Count];
object[] FIELD2 = new object[listDTO.Count];
for (int i = 0; i <= listDTO.Count - 1; i++)
{
ID[i] = listDTO.Id;
FIELD1[i] = listDTO.Field1;
FIELD2[i] = listDTO.Field2;
}
OraCommand.ArrayBindCount = listDTO.Count;
OraCommand.Parameters.Add(":ID", OracleDbType.Decimal, ID, System.Data.ParameterDirection.Input);
OraCommand.Parameters.Add(":FIELD1", OracleDbType.Varchar2, 10, FIELD1, System.Data.ParameterDirection.Input);
OraCommand.Parameters.Add(":FIELD2", OracleDbType.Varchar2, 32, FIELD2, System.Data.ParameterDirection.Input);
db.DoSqlPrepareCommand(OraCommand);
Edit: This is how I think it should best be done using Npgsql:
NpgsqlConnection conn = new NpgsqlConnection("connString");
conn.Open();
NpgsqlCommand command = new NpgsqlCommand();
string CommandText = "";
for (int i = 0; i <=5 ; i++)
{
CommandText = CommandText + "INSERT INTO testtbl (id, field1) VALUES (@ID_" + i + " , @FIELD1_" + i + ");";
command.Parameters.Add(new NpgsqlParameter("ID_" + i, i));
command.Parameters.Add(new NpgsqlParameter("FIELD1_" + i, "FIELD1" + i));
}
command.CommandText = CommandText;
command.Connection = conn;
int result = command.ExecuteNonQuery();
回答1:
If what you're looking for is bulk insert of many rows, you should look at binary COPY - this is definitely the most efficient method.
Otherwise it's definitely possible to prepare your INSERT statement and then batch/pipeline its execution with different parameters in the same roundtrip. This will yield very good performance, although still not as good as binary COPY.
来源:https://stackoverflow.com/questions/44260860/array-binding-with-npgsql