SQL code to insert multiple rows in ms-access table

后端 未结 8 1680
北荒
北荒 2020-12-15 14:01

I\'m trying to speed up my code and the bottleneck seems to be the individual insert statements to a Jet MDB from outside Access via ODBC. I need to insert 100 rows at a tim

相关标签:
8条回答
  • 2020-12-15 14:33

    Not that I am aware of. And I have felt this pain before. The good news is that if you wrap the insert in a transaction and don't close the connection between each call (eg--pass the command as a parameter) then it is orders of magnitude quicker than open()->INSERT->close() is.

    Use a code pattern something like:

    using (DbConnection conn = new OdbcConnection())
    using (DbCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "INSERT INTO foo(bar) VALUES (@bar)";
        DbParameter p = cmd.CreateParameter();
        p.ParameterName = "@bar";
        cmd.CommandType = CommandType.Text;
        conn.Open();
        using (DbTransaction tran = conn.BeginTransaction())
        {
            cmd.Transaction = tran;
            try
            {
                for (int i = 0; i < 1000; i++)
                {
                    p.Value = i;
                    cmd.ExecuteNonQuery();
                }
                tran.Commit();
                conn.Close();
            }
            catch (Exception)
            {
                tran.Rollback();
                throw;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-15 14:34

    Your query should look like this

    insert into aaa (col1, col2)
    select * from (select 'yourdatarow1col1' as col1 , 'yourdatarow1col2' as col2 from ffffd
    union all
    select 'yourdatarow2col1' as col1, 'yourdatarow1col2' as col2 from ffffd) as tmp
    

    aaa: Is your target table in access

    ffffd: create a table in access db with one colum and must have 1 row, doesn't not mater what data.

    aliases: All aliases should have same name and order has target table

    Hope works for you, my process drop from 15 minutes to 1.30 minutes

    Bye Gus

    0 讨论(0)
提交回复
热议问题