Transfer data from table to table in sqlserver

SqlBulkCopy class

 

link: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx

 

remarks:

 

Microsoft SQL Server includes a popular command-prompt utility named bcp for moving data from one table to another, whether on a single server or between servers. The SqlBulkCopy class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but SqlBulkCopy offers a significant performance advantage over them.

The SqlBulkCopy class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.

 

C# exmaple:

 

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;";
    }
}
It also can transfer data from Xml file to database table.
link:http://www.codeproject.com/KB/database/TransferUsingSQLBulkCopy.aspx

Transferring Data from XML File to Database Table

The data source is not only limited to database tables, but you can also use XML files. Here is a very simple XML file which is used as a source for the bulk copy operation. (Products.xml)

 

<?xml version="1.0" encoding="utf-8" ?>

<Products>
  <Product productID="1" productName="Chai" />
  <Product productID="2" productName="Football" />
  <Product productID="3" productName="Soap" />
  <Product productID="4" productName="Green Tea" />
</Products>


 

private static void PerformBulkCopyXMLDataSource()
{
    string connectionString =
            @"Server=localhost;Database=Northwind;Trusted_Connection=true";
    DataSet ds = new DataSet();
    DataTable sourceData = new DataTable();
    ds.ReadXml(@"C:/Products.xml");
    sourceData = ds.Tables[0];
    // open the destination data
    using (SqlConnection destinationConnection =
                    new SqlConnection(connectionString))
    {
        // open the connection
        destinationConnection.Open();
        using (SqlBulkCopy bulkCopy =
                    new SqlBulkCopy(destinationConnection.ConnectionString))
        {
            // column mappings
            bulkCopy.ColumnMappings.Add("productID", "ProductID");
            bulkCopy.ColumnMappings.Add("productName", "Name");
            bulkCopy.DestinationTableName = "Products_TopSelling";
            bulkCopy.WriteToServer(sourceData);
        }
    }
}

The file is first read into the DataTable and then fed to the WriteToServer method of the SqlBulkCopy class. Since, the destination table is Products_TopSelling, we had to perform the column mapping.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
该错误是由于Maven在获取com.microsoft.sqlserver:sqljdbc4:pom:4.0的时候无法传输该文件造成的。 这个错误通常是由于以下原因导致的: 1. 服务器连接问题:可能是由于网络问题或者Maven配置错误导致无法连接到远程服务器。可以尝试检查网络连接是否正常,并且确保Maven的配置文件中的远程仓库地址正确。 2. 仓库配置错误:可能是由于Maven的配置文件中没有正确配置远程仓库信息。可以检查Maven配置文件(settings.xml)中的<repositories>和<mirrors>节点,确保远程仓库配置正确。 3. 仓库中没有该文件:可能是由于远程仓库中不存在com.microsoft.sqlserver:sqljdbc4:pom:4.0这个文件。可以尝试在浏览器中访问仓库地址,确认该文件是否存在。 解决这个问题的方法可以有以下几种: 1. 检查网络连接:确保网络连接正常,可以尝试重新启动网络设备或者更换网络环境,然后重新执行Maven命令。 2. 检查Maven配置:确保Maven的配置文件中远程仓库的地址正确,可以尝试使用其他可用的远程仓库进行下载。 3. 更新Maven仓库:可以尝试清理并更新本地的Maven仓库,重新下载该文件。 最后,还可以尝试使用Maven的一些常用命令进行故障排除,如`mvn clean install -U`来强制更新本地仓库,或者使用`mvn dependency:purge-local-repository`来清理本地仓库。如果问题仍然存在,可以考虑使用其他方式获取该文件,如手动下载并安装到本地仓库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值