首先,在Asp.Net中使用Bulk实现批量插入数据的步骤如下:
- 创建一个DataTable对象,然后用Add方法添加字段。如下所示:
csharp
DataTable dt = new DataTable();
dt.Columns.Add("ID",typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("Sex", typeof(string));
- 添加数据至DataTable中。如下所示:
```csharp
DataRow dr = dt.NewRow();
dr["ID"] = 1;
dr["Name"] = "张三";
dr["Age"] = 22;
dr["Sex"] = "男";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 2;
dr["Name"] = "李四";
dr["Age"] = 20;
dr["Sex"] = "女";
dt.Rows.Add(dr);
```
- 使用SqlBulkCopy类将数据批量插入数据库中。如下所示:
```csharp
using (SqlConnection connection = new SqlConnection(strConnectionString)) //strConnectionString是数据库连接字符串
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName = "test"; //这里的test是要插入的表
bulkCopy.WriteToServer(dt); //将DataTable中的数据写入到数据库中
}
}
```
下面给出两个使用Bulk实现批量插入数据的示例:
- 将Excel数据批量插入SQL Server表中,代码如下:
```csharp
string strConnectionString = "Data Source=.;Initial Catalog=testdb;User ID=sa;Password=123456;";
string strExcelPath = "D:\test.xlsx";
string strSheetName = "Sheet1"; //Excel中的表名和SQL Server中要插入的表名必须相同
using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strExcelPath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'"))
{
connection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM ["+ strSheetName + "$]", connection);
DataTable dtExcel = new DataTable();
adapter.Fill(dtExcel);
using (SqlConnection con = new SqlConnection(strConnectionString))
{
con.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
{
bulkCopy.DestinationTableName = strSheetName;
bulkCopy.WriteToServer(dtExcel);
}
}
}
```
- 批量插入Excel数据到MySQL中,代码如下:
```csharp
string strConnectionString = "server=localhost;database=testdb;uid=root;pwd=123456;";
string strExcelPath = "D:\test.xlsx";
string strSheetName = "Sheet1";
using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strExcelPath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'"))
{
connection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + strSheetName + "$]", connection);
DataTable dtExcel = new DataTable();
adapter.Fill(dtExcel);
using (MySqlConnection con = new MySqlConnection(strConnectionString))
{
con.Open();
using (MySqlBulkCopy bulkCopy = new MySqlBulkCopy(con))
{
bulkCopy.DestinationTableName = strSheetName;
bulkCopy.WriteToServer(dtExcel);
}
}
}
```
以上就是Asp.Net使用Bulk实现批量插入数据的完整攻略,希望能够帮助到你。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Asp.Net使用Bulk实现批量插入数据 - Python技术站