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

大家看看。动态插入SQL表问题,。
代码如下:
      for(int   i=0;i <   ds.Tables[0].Rows.Count;i++)
                {                                            
                        string   sqlstr   =   "insert   into   "   +   DropDownList2.Text   +   "   values   ( ' "   +   ds.Tables[0].Rows[i][0].ToString()   +   " ', ' "   +   ds.Tables[0].Rows[i][1].ToString()   +   " ', ' "   +   ds.Tables[0].Rows[i][2].ToString()   +   " ', ' "   +   ds.Tables[0].Rows[i][3].ToString()   +   " ') ";
                        SqlCommand   com2   =   new   SqlCommand(sqlstr,   con);                
                        com2.ExecuteNonQuery();                
                }
这个是列固定的情况下好办,但是如果表中的列数不知道,用
for   (int   j   =   0;   j   <   ds.Tables[0].Columns.Count;   j++)循环可以吗?
。。
那应该怎么做,,??

------解决方案--------------------
for(int i=0;i < ds.Tables[0].Rows.Count;i++)
{
stringbuilder builder=new stringbuilder();
builder.append( "insert into " + DropDownList2.Text + " values ( ");
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
if(j!=ds.Tables[0].Columns.Count-1)
{
builder.append( " ' " + ds.Tables[0].Rows[i][j].ToString() + " ', ' " );
}
else
{
builder.append( " ' " + ds.Tables[0].Rows[i][j].ToString() + " ' " );
}
}
SqlCommand com2 = new SqlCommand(builder.tostring(), con);
com2.ExecuteNonQuery();

}

------解决方案--------------------
up~~~~~~~~~~~~~