第一种,最常见的Executenonquery(返回影响的行数)sql是我的查询插入语句,你可以换成你的!这种方式入库,速度一般,大量数据时不提倡使用
///
/// 通过table一个一个的插入
///
///
public static void Executenonquery(DataTable table)
{
foreach (DataRow itemRow in table.Rows)
{
//if exists(select * from dbo.ID where ENG = '')
// begin
// return;
// end
//else
// begin
// INSERT INTO ID([ENG],[GB],[B5],[FILE],[MSG]) values('', '', '', '', '')
// end
string sql = "if exists(select * from " + table.TableName + " where ENG = '" + itemRow["ENG"].ToString() + "') "+
" begin return; end else begin INSERT INTO " + table.TableName + "([ENG],[GB],[B5],[FILE],[MSG])" +
"VALUES('" + itemRow["ENG"].ToString() + "'" +
",'" + itemRow["GB"].ToString() + "'" +
",'" + itemRow["B5"].ToString() + "'" +
",'" + itemRow["FILE"].ToString() + "'" +
",'" + itemRow["MSG"].ToString() + "') end";
using (SqlConnection sqlconn = new SqlConnection(connectString))
{
sqlconn.Open();
SqlCommand sqlcommand = new SqlCommand(sql, sqlconn);
sqlcommand.ExecuteNonQuery();
sqlconn.Close();
}
}
}
2,通过adapter入库,这种入库,起先,你需要先把datatable放入到dataset中然后进行入库,这种方式主要是对库中对应的表进行增删改,方便使用(效率只比第一种方式好点)
///
/// 通过adapter更新数据库
///
///
public static void DataadapterInssert(DataSet dataset)
{
if (dataset.Tables.Count > 0)
{
foreach (DataTable itemTable in dataset.Tables)
{
SqlCommand insertcommand = new SqlCommand("if exists(select * from " + itemTable.TableName + " where ENG = @ENG) begin return; end "+
" else begin INSERT INTO " + itemTable.TableName + "([ENG],[GB],[B5],[FILE],[MSG])" +
"VALUES(@ENG, @GB,@B5,@FILE,@MSG) end", new SqlConnection(connectString));
insertcommand.Parameters.Add("@ENG", SqlDbType.VarChar, 100, "ENG");
insertcommand.Parameters.Add("@GB", SqlDbType.VarChar, 100, "GB");
insertcommand.Parameters.Add("@B5", SqlDbType.VarChar, 200, "B5");
insertcommand.Parameters.Add("@FILE", SqlDbType.VarChar, 200, "FILE");
insertcommand.Parameters.Add("@MSG", SqlDbType.VarChar, 100, "MSG");
SqlDataAdapter sqldataadapter = new SqlDataAdapter();
sqldataadapter.InsertCommand = insertcommand;
sqldataadapter.Update(dataset, itemTable.TableName);
}
}
}
3,重头戏都在最后,这种方式速度比前两种快很多,适合用于大量数据插入更新,也将datatable放入dataset中然后通过遍历,将datatable复制到数据库中对应的表中,快速便捷
/
//
/// 通过SqlBulkCopy复制table数据到数据库
///
///
public static void SqlbulkcopyInsert(DataSet dataset)
{
string ie;
if (dataset.Tables.Count > 0)
{
foreach (DataTable itemTable in dataset.Tables)
{
SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectString, SqlBulkCopyOptions.UseInternalTransaction);
sqlbulkcopy.DestinationTableName = itemTable.TableName;//数据库中的表名
for (int i = 0; i < itemTable.Rows.Count; i++)
{
ie = itemTable.Rows[i][2].ToString();
}
sqlbulkcopy.WriteToServer(itemTable);
}
}
}