zoukankan      html  css  js  c++  java
  • PetaPoco 批量插入数据

    网上找的代码,还没经过验证

    /// <summary>
        /// Bulk inserts multiple rows to SQL
        /// </summary>
        /// <param name="tableName">The name of the table to insert into</param>
        /// <param name="primaryKeyName">The name of the primary key column of the table</param>
        /// <param name="autoIncrement">True if the primary key is automatically allocated by the DB</param>
        /// <param name="pocos">The POCO objects that specifies the column values to be inserted</param>
        /// <param name="batchSize">The number of POCOS to be grouped together for each database rounddtrip</param>        
        public void BulkInsert(string tableName, string primaryKeyName, bool autoIncrement, IEnumerable<object> pocos, int batchSize = 25)
        {
            try
            {
                OpenSharedConnection();
                try
                {
                    using (var cmd = CreateCommand(_sharedConnection, ""))
                    {
                        var pd = PocoData.ForObject(pocos.First(), primaryKeyName);
                        // Create list of columnnames only once
                        var names = new List<string>();
                        foreach (var i in pd.Columns)
                        {
                            // Don't insert result columns
                            if (i.Value.ResultColumn)
                                continue;
    
                            // Don't insert the primary key (except under oracle where we need bring in the next sequence value)
                            if (autoIncrement && primaryKeyName != null && string.Compare(i.Key, primaryKeyName, true) == 0)
                            {
                                // Setup auto increment expression
                                string autoIncExpression = _dbType.GetAutoIncrementExpression(pd.TableInfo);
                                if (autoIncExpression != null)
                                {
                                    names.Add(i.Key);
                                }
                                continue;
                            }
                            names.Add(_dbType.EscapeSqlIdentifier(i.Key));
                        }
                        var namesArray = names.ToArray();
    
                        var values = new List<string>();
                        int count = 0;
                        do
                        {
                            cmd.CommandText = "";
                            cmd.Parameters.Clear();
                            var index = 0;
                            foreach (var poco in pocos.Skip(count).Take(batchSize))
                            {
                                values.Clear();
                                foreach (var i in pd.Columns)
                                {
                                    // Don't insert result columns
                                    if (i.Value.ResultColumn) continue;
    
                                    // Don't insert the primary key (except under oracle where we need bring in the next sequence value)
                                    if (autoIncrement && primaryKeyName != null && string.Compare(i.Key, primaryKeyName, true) == 0)
                                    {
                                        // Setup auto increment expression
                                        string autoIncExpression = _dbType.GetAutoIncrementExpression(pd.TableInfo);
                                        if (autoIncExpression != null)
                                        {
                                            values.Add(autoIncExpression);
                                        }
                                        continue;
                                    }
    
                                    values.Add(string.Format("{0}{1}", _paramPrefix, index++));
                                    AddParam(cmd, i.Value.GetValue(poco), i.Value.PropertyInfo);
                                }
    
                                string outputClause = String.Empty;
                                if (autoIncrement)
                                {
                                    outputClause = _dbType.GetInsertOutputClause(primaryKeyName);
                                }
    
                                cmd.CommandText += string.Format("INSERT INTO {0} ({1}){2} VALUES ({3})", _dbType.EscapeTableName(tableName),
                                                                 string.Join(",", namesArray), outputClause, string.Join(",", values.ToArray()));
                            }
                            // Are we done?
                            if (cmd.CommandText == "") break;
                            count += batchSize;
                            DoPreExecute(cmd);
                            cmd.ExecuteNonQuery();
                            OnExecutedCommand(cmd);
                        }
                        while (true);
    
                    }
                }
                finally
                {
                    CloseSharedConnection();
                }
            }
            catch (Exception x)
            {
                if (OnException(x))
                    throw;
            }
        }
    
    
        /// <summary>
        /// Performs a SQL Bulk Insert
        /// </summary>
        /// <param name="pocos">The POCO objects that specifies the column values to be inserted</param>        
        /// <param name="batchSize">The number of POCOS to be grouped together for each database rounddtrip</param>        
        public void BulkInsert(IEnumerable<object> pocos, int batchSize = 25)
        {
            if (!pocos.Any()) return;
            var pd = PocoData.ForType(pocos.First().GetType());
            BulkInsert(pd.TableInfo.TableName, pd.TableInfo.PrimaryKey, pd.TableInfo.AutoIncrement, pocos);
        }

    摘自:http://stackoverflow.com/questions/6595105/bulk-insert-update-with-petapoco/14479073

  • 相关阅读:
    恢复oracle中误删除drop掉的表
    mysql安装教程(小白入门)
    各版本mysql下载安装教程(超详细,超全)
    Jetbrains系列产品2019.3.3及以下版本最新激活方法
    老友记全季高清视频(中英字幕)及学习资料(剧本,音频,台词)等等!
    电脑桌面快捷方式小箭头的去与留!
    Sublime Text 3破解教程及应用技巧和诀窍(完美激活)
    7个堪称经典的电脑小技巧,让你办公事半功倍!
    怎么优化,美化电脑桌面(Fences v3.0.9 中文破解版)来这里教你。
    JAVA
  • 原文地址:https://www.cnblogs.com/haight/p/5208682.html
Copyright © 2011-2022 走看看