打印本文 打印本文 关闭窗口 关闭窗口
批量更新数据库表中的数据
作者:武汉SEO闵涛  文章来源:敏韬网  点击数1526  更新时间:2009/6/9 2:35:17  文章录入:mintao  责任编辑:mintao

/// <summary>
  /// 更新内存中的数据到数据库
  /// </summary>
  /// <param name="tableName"></param>
  public void UpdateDataSetToDB(string tableName)
  {
   HttpContext.Current.Application.Lock();
   try
   {
    DataSet myDS=(DataSet)HttpContext.Current.Application["aDataSet"];
    SqlDataAdapter myDA= (SqlDataAdapter)HttpContext.Current.Application["aDA"];
    SqlCommandBuilder sbTemp=new SqlCommandBuilder(myDA);
    myDA.Update(myDS,tableName);
   }
   catch(Exception ex)
   {
    WebLog.WriteLog("更新内存中的数据到数据库出现了错误:" + ex.Message);
   }
   HttpContext.Current.Application.UnLock();
  }

 

 

我写的一个更新一个datable的方法,给你参考一下

public string ExecuteInsert(DataTable dt)
  {
   
   string sql="";
   string fieldStr="";
   string valueStr="";
   int i=0;
   string result;
   try
   { 
    
    for(i=0;i<dt.Columns.Count;i++)
    {
     fieldStr += dt.Columns[i].ColumnName + ",";     
    }

    fieldStr = fieldStr.Substring(0,fieldStr.Length-1);   
   
    for(i=0;i<dt.Rows.Count;i++)
    {
     sql = "insert into {0}({1}) values({2})";
     valueStr ="";
     for(int j=0;j<dt.Columns.Count;j++)
     {
      
      switch(System.Type.GetTypeCode(dt.Rows[i][j].GetType()))
      {
       case System.TypeCode.Byte:
       case System.TypeCode.Char:
       case System.TypeCode.Decimal:
       case System.TypeCode.Double:
       case System.TypeCode.Int16:
       case System.TypeCode.Int32:
       case System.TypeCode.Int64:
       case System.TypeCode.SByte:
       case System.TypeCode.Single:
       case System.TypeCode.UInt16:
       case System.TypeCode.UInt32:
       case System.TypeCode.UInt64:
        valueStr += dt.Rows[i][j].ToString() +",";
        break;
       case System.TypeCode.DateTime:
       case System.TypeCode.String:       
        valueStr += "'" + dt.Rows[i][j].ToString() +"',";
        break;
       case System.TypeCode.Boolean:
       {
        if ((bool)dt.Rows[i][j]==true)
         valueStr += "1,";
        else
         valueStr += "0,";

        break;
       }
       default:
        valueStr +=" null,";
        break; 
        }      
      }
     
     valueStr = valueStr.Substring(0,valueStr.Length-1); 
     sql = string.Format(sql,dt.TableName,fieldStr,valueStr);
     result = this.ExecuteNonQuery(sql);
    
    }
    
    
    return "ok";
   }

   catch(Exception ex)
   {
    return ex.Message;

   }
  }

打印本文 打印本文 关闭窗口 关闭窗口