日期:2014-05-18  浏览次数:20482 次

C#,将DataTable中的数据批量导入到Oracle数据库中
我尝试着用SQLServer的方法批量导入了一下,但是Update方法不执行,也不报异常,我的代码如下:
C# code

    private OracleDataAdapter odad;
   public static int InsertBatch(DataTable dt, List<OracleType> DbTypeList,string strtable)
    {
        getConnection();
        int count = 0;
        string strfields = "";
        string strvalues = "";
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            string strfiled = dt.Columns[i].ColumnName;
            strfields += strfiled + ",";
            strvalues += "@" + strfiled + ",";
        }
        if (strfields != "")
        {
            strfields = strfields.Substring(0, strfields.LastIndexOf(","));
            strvalues = strvalues.Substring(0, strvalues.LastIndexOf(","));
        }

        try
        {
            if (ocon.State != ConnectionState.Open) ocon.Open();
            odad = new OracleDataAdapter();
            //建立InsertCommand
            StringBuilder sb = new StringBuilder("");
            sb.Append("INSERT into " + strtable + " (" + strfields + ") VALUES(");
            sb.Append(strvalues + ")");
            odad.InsertCommand = new OracleCommand();
            odad.InsertCommand.CommandText = sb.ToString();
            odad.InsertCommand.Connection = ocon;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                string filed = dt.Columns[i].ColumnName;
                string strvalue = "@" + filed;
                OracleParameter oparam = new OracleParameter();
                oparam.ParameterName = strvalue;
                oparam.OracleType = DbTypeList[i];
                oparam.SourceVersion = DataRowVersion.Current;
                oparam.SourceColumn = filed;
                odad.InsertCommand.Parameters.Add(oparam);
            }
            count = odad.Update(dt);
        }
        catch (Exception ex)
        {
            count = 0;
        }
        finally
        {
            if (ocon != null)
                ocon.Close();
        }
        return count;
    }



方法中的参数List<OracleType> DbTypeList,是与dt中每一列一一对应的
执行到count = odad.Update(dt);的时候没有异常,也并未将数据插入到数据库中,请问各位,怎么才能执行DataTable的批量导入Oracle数据库操作啊?

------解决方案--------------------
如果是Oracle 11G的话可以引用Oracle.DataAccess.dll中使用OracleBulkCopy批量导入数据,效率很高

 catch (Exception ex)
{
count = 0;
}
异常被捕获掉了,你可以去掉之后看是不是报异常
------解决方案--------------------
事务是批量导入的关键
------解决方案--------------------
是不得用Command.Prepare()
------解决方案--------------------
楼主好像忘记设置oparam.Value了