在我们平时的开发过程中,经常要向数据库插入数据,有时可能要进行很多次类似的操作,比如向数据库中的同一个表同时插入若干数据,即批量插入数据。
向数据库中批量插入数据,可以将若干条数据一次插入道数据库,提高程序的执行效率,也可以减少我们的工作量。
批量插入数据,可以采用一下两种方法。
一、利用事务(transaction)
‘定义执行批量插入数据的函数,参数为insert SQL语句的数组
sub ExeTransaction (Byval Sqlstrlist as string())
dim Conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Tax.mdb"
dim trans as OledbTransaction=Nothing
try
if conn.State=connectionstate.closed then
conn.open()
end if
dim cmd as oledbCommand=new oledbcommand()
cmd.connection=conn
cmd.commandtype=commandtype.text
trans=conn.begintransaction()
cmd.transaction=trans
dim I as integer
for I=0 to Sqlstrlist.GetupperBound(0)
cmd.commandtext= Sqlstrlist(i) ‘取得参数(数组)中的值
cmd.executenonquery()
next
trans.commit()
catch ex as oledbexception
trans.rollback()
fanlly
conn.close()
end try
end sub
二、利用dataset
public sub Insert()
‘建立datatable数据源
dim dt as DataTable=New DataTable()
dim dr as DataRow
dt.columns.add(new DataColumn(“name”))
dim j as Integer
for j =0 to 10
dr=dt.newrow()
dr(0)=”name”+j.tostring
dt.rows.add(dr)
next
dim Conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Tax.mdb"
conn.open()
dim MyAdapter as Oledbdataadapter=new OleDataAdapter()
….
dim cmd as Oledbcommand=New Oledbcommand(“Insert Into table(name) values (@name)”,conn)
cmd.parameters.item(“@name”).SourceColumns=dt.columns(“name”).columnsName
myadapter.update(dt)
conn.close()
end sub
利用以上的两种方法,都可以完成向数据库批量插入数据。
如果你使用的asp.net2.0,你可以使用SqlBulkCopy批量导入数据
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
new SqlConnection(connectionString))
{
sourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new SqlCommand(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader =
commandSourceData.ExecuteReader();
// Open the destination connection. In the real world you would
// not use SqlBulkCopy to move data from one table to the other
// in the same database. This is for demonstration purposes only.
using (SqlConnection destinationConnection =
new SqlConnection(connectionString))
{
destinationConnection.Open();
// Set up the bulk copy object.
// Note that the column positions in the source
// data reader match the column positions in
// the destination table so there is no need to
// map columns.
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Close the SqlDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the using block.
reader.Close();
}
}
// Perform a final count on the destination
// table to see how many rows were added.
long countEnd = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Ending row count = {0}", countEnd);
Console.WriteLine("{0} rows were added.", countEnd - countStart);
Console.WriteLine("Press Enter to finish.");
Console.ReadLine();
}
}
}
private static string GetConnectionString()
// To avoid storing the sourceConnection string in your code,
// you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
"Initial Catalog=AdventureWorks;";
}
}