ความสามมรถใหม่ของ VS2005 ในการใช่งาน SqlBulkCopy


การใช้งาน SqlBulkCopy


SqlBulkCopy เป็น class ที่ใช้ในการ Imports Data

โดยเป็นความสามารถอีกอย่างหนึ่งของ VS2005

 

private static void CopyDataToBulkCopyDemoMatchingColumns()
 {
  Console.WriteLine("Copying data to BulkCopyDemoMatchingColumns table...");

  SqlConnection sourceConnection = new SqlConnection(GetConnectionString());
        SqlConnection destConnection = new SqlConnection(GetConnectionString());
        SqlDataReader reader = null;

  try
  {
   // Open connections to the Adventure Works database, to read and write data.
   sourceConnection.Open();
            destConnection.Open();

   // Perform an initial count on the destination table.
            SqlCommand commandRowCount = new SqlCommand(
                    "SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;",
                    destConnection);

            int countStart = (int)commandRowCount.ExecuteScalar();
            Console.WriteLine("Starting row count = " + countStart);

   // Get data from the source table as a SqlDataReader.
   SqlCommand commandSourceData = new SqlCommand(
    "SELECT ProductID, Name, ProductNumber, ListPrice FROM Production.Product;",
    sourceConnection);
   reader = commandSourceData.ExecuteReader();

   // Set up the bulk copy object.
   // The column positions in the source data reader match those
   // in the destination table, so there is no need to map columns.
            SqlBulkCopy bcp = new SqlBulkCopy(destConnection);
   bcp.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns";
   bcp.BatchSize = 20;

   // Write from the source to the destination.
   bcp.WriteToServer(reader);
   bcp.Close();

   // Find out how many rows were added to the destination table.
            int countEnd = (int)commandRowCount.ExecuteScalar();
            Console.WriteLine("Ending row count = " + countEnd);
            Console.WriteLine(countEnd - countStart + " rows were added.");
  }
  catch (Exception ex)
  {
   Console.WriteLine("An exception occurred: {0}", ex.Message);
  }
  finally
  {
   if (sourceConnection != null)
    sourceConnection.Close();

            if (destConnection != null)
                destConnection.Close();

            if (reader != null)
                reader.Close();
  }
  Console.WriteLine("-----------------------------------------------------");
 }

คำสำคัญ (Tags): #vs2005#dts#sqlbulkcopy
หมายเลขบันทึก: 128026เขียนเมื่อ 14 กันยายน 2007 12:57 น. ()แก้ไขเมื่อ 11 กุมภาพันธ์ 2012 20:24 น. ()สัญญาอนุญาต: จำนวนที่อ่านจำนวนที่อ่าน:


ความเห็น (0)

ไม่มีความเห็น

พบปัญหาการใช้งานกรุณาแจ้ง LINE ID @gotoknow
ClassStart
ระบบจัดการการเรียนการสอนผ่านอินเทอร์เน็ต
ทั้งเว็บทั้งแอปใช้งานฟรี
ClassStart Books
โครงการหนังสือจากคลาสสตาร์ท