OracleBulkCopy does not insert entries to table

2019-05-28 10:36发布

问题:

Here's the code I'm executing:

public static void Main(string[] args)
{
    var connectionString = "Data Source=dbname;User Id=usrname;Password=pass;";
    DataTable dt = new DataTable("BULK_INSERT_TEST");
    dt.Columns.Add("N", typeof(double));
    var row = dt.NewRow();
    row["N"] = 1;
    using (var connection = new OracleConnection(connectionString)){
        connection.Open();
        using(var bulkCopy = new OracleBulkCopy(connection, OracleBulkCopyOptions.UseInternalTransaction))
        {
            bulkCopy.DestinationTableName = dt.TableName;
            bulkCopy.WriteToServer(dt);
        }
    }

    using (var connection = new OracleConnection(connectionString)){
        connection.Open();
        var command = new OracleCommand("select count(*) from BULK_INSERT_TEST", connection);
        var res = command.ExecuteScalar();
        Console.WriteLine(res); // Here I'm getting 0
    }
}

It uses OracleBulkCopy to insert 1 entry to table and then it counts rows in the table. Why am I getting 0 rows? Here's the structure of table:

-- Create table
create table BULK_INSERT_TEST
(
  n NUMBER
)

回答1:

You haven't actually added the row to the table. You've used the table to create a new row with the right columns, but not actually added it to the table. You need:

dt.Rows.Add(row);

(before your first using statement, basically)