通过DataTable动态生成插入语句,动态添加字段和数据,这是我写的代码,请高手看下,有没有更好的解决方法
publicstaticvoidinsertTables(DataTabledt,stringtableName){for(intk=0;k<dt.Rows.Count;...
public static void insertTables(DataTable dt,string tableName)
{
for (int k = 0; k < dt.Rows.Count; k++) //获取DataTable表的行
{
List<SqlParameter> list = new List<SqlParameter>(); //创建一个SqlParameter的数组,用来装载便利后的SqlParameter
string sql = "insert into " + tableName + "("; //拼sql语句
for (int i = 0; i < dt.Columns.Count; i++) //循环遍历DataTable表的字段名称
{
if (i == dt.Columns.Count - 1)
{
sql += dt.Columns[i].ColumnName + ")"; //动态获取DataTable表的字段名称,并添加到sql语句
}
else
{
sql += dt.Columns[i].ColumnName + ",";
}
}
sql += " values (";
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j == dt.Columns.Count - 1)
{
sql += "@row" + j + ")";
}
else
{
sql += "@row" + j + ",";
}
DataRow row = dt.Rows[k]; //获取Datatable当前的行
list.Add(new SqlParameter("@row" + j, row[j])); //定义SqlParameter传参并添加到list数组
}
SqlParameter[] sp = list.ToArray(); //定义SqlParameter[]数组接收List<SqlParameter>
new DBHelper().GetExcuteNonQuery(sql, sp); //执行
}
} 展开
{
for (int k = 0; k < dt.Rows.Count; k++) //获取DataTable表的行
{
List<SqlParameter> list = new List<SqlParameter>(); //创建一个SqlParameter的数组,用来装载便利后的SqlParameter
string sql = "insert into " + tableName + "("; //拼sql语句
for (int i = 0; i < dt.Columns.Count; i++) //循环遍历DataTable表的字段名称
{
if (i == dt.Columns.Count - 1)
{
sql += dt.Columns[i].ColumnName + ")"; //动态获取DataTable表的字段名称,并添加到sql语句
}
else
{
sql += dt.Columns[i].ColumnName + ",";
}
}
sql += " values (";
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j == dt.Columns.Count - 1)
{
sql += "@row" + j + ")";
}
else
{
sql += "@row" + j + ",";
}
DataRow row = dt.Rows[k]; //获取Datatable当前的行
list.Add(new SqlParameter("@row" + j, row[j])); //定义SqlParameter传参并添加到list数组
}
SqlParameter[] sp = list.ToArray(); //定义SqlParameter[]数组接收List<SqlParameter>
new DBHelper().GetExcuteNonQuery(sql, sp); //执行
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询