/// <summary>
/// 入库datatable
/// </summary>
/// <param name="dt">数据</param>
/// <param name="connectString">数据库链接字符串</param>
public void DataTableToSQLServer(DataTable dt, string connectString)
{
string connectionString = connectString;
using (SqlConnection destinationConnection = new SqlConnection(connectionString))
{
destinationConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
{
try
{
bulkCopy.DestinationTableName = "checkinout";//要插入的表的表名
bulkCopy.BatchSize = dt.Rows.Count;
//映射字段名 DataTable列名,数据库对应的列名
bulkCopy.ColumnMappings.Add("ID", "ID");
bulkCopy.ColumnMappings.Add("TIME", "TIME");
bulkCopy.WriteToServer(dt);
Console.WriteLine("添加完成,数量:"+ dt.Rows.Count.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
/// <summary>
/// 创建DataTable例子
/// </summary>
/// <returns></returns>
public DataTable CreateDataTable()
{
DataTable tblDatas = new DataTable("Datas");
tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
tblDatas.Columns.Add("Name", Type.GetType("System.String"));
//添加100行数据
for(int i=0;i<100;i++)
{
DataRow newRow = tblDatas.NewRow();
newRow["ID"] = i;
newRow["Name"] = "Name"+i.ToString();
tblDatas.Rows.Add(newRow);
}
return tblDatas;
}