将DataTable的TableName属性设置为数据库中表的名称,然后调用该方法
public static string ExecuteInsert(DataTable dt)
{
string sql="";
string fieldStr="";
string valueStr="";
int i=0;
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);
ExecuteNonQuery(sql);
}
return "ok";
}
catch(Exception ex)
{
return ex.Message;
}
}