加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – bulkCopy.WriteToServer不复制

发布时间:2020-12-15 22:14:03 所属栏目:百科 来源:网络整理
导读:我正在尝试使用bulkCopy.WriteToServer()将数据从远程SQL Server Express复制到本地SQL Server Express,但是没有数据写入我的本地SQL Server Express数据库. 代码立即跳过WriteToServer()方法…我不知道它是否在内部失败并且没有显示错误消息 我已阅读How to
我正在尝试使用bulkCopy.WriteToServer()将数据从远程SQL Server Express复制到本地SQL Server Express,但是没有数据写入我的本地SQL Server Express数据库.

代码立即跳过WriteToServer()方法…我不知道它是否在内部失败并且没有显示错误消息

我已阅读How to duplicate a SQL Server 2000 table programatically using .NET 2.0?,而且我使用的代码非常相似.虽然我在远程和SQL Server 2014 Express本地使用SQL Server 2008 Express:

using (SqlConnection remoteConnection = new SqlConnection(remoteConnectionString))
{
    var query = "SELECT * FROM information_schema.tables WHERE table_type = 'base table'";
    SqlCommand commandGetTables = new SqlCommand(query,remoteConnection);

    try
    {
        remoteConnection.Open();
        SqlDataReader results = commandGetTables.ExecuteReader();

        while (results.Read())
        {
            tables.Add(results.GetString(2));
        }

        results.Close();
    }
    catch (Exception ex)
    {
        //stuff
    }
    finally
    {
        remoteConnection.Close();
    }

    remoteConnection.Open();

    foreach (var table in tables)
    {                    
        // Get data from the source table as a SqlDataReader.
        var commandSourceData = new SqlCommand("SELECT * FROM " + table + ";",remoteConnection);
        var reader = commandSourceData.ExecuteReader();

        using (SqlConnection destinationConnection = new SqlConnection(destinationConnectionString))
        {
            destinationConnection.Open();

            using (var bulkCopy = new SqlBulkCopy(destinationConnection))
            {
                bulkCopy.DestinationTableName = table;

                try
                {
                    // Write from the source to the destination.
                    bulkCopy.WriteToServer(reader);
                }
                catch (Exception ex)
                {
                    //stuff
                }
                finally
                {
                    //stuff removed for this post
                }
            }
        }
    }

    remoteConnection.Close();
}
return true;

我知道这可能会受到SQL注入等的影响,但这个应用程序仅供我使用而不是此处的问题.

我究竟做错了什么?

编辑

我检查了reader的值(var reader = commandSourceData.ExecuteReader();)并且它有我想要的条目,这意味着他从遥控器读取是正常的.

解决方法

bulkCopy.DestinationTableName = table;
bulkCopy.WriteToServer(reader);

这些线是错的它应该看起来像这样..

bulkCopy.DestinationTableName = "dbo." + DataTable.TableName; 
bulkCopy.WriteToServer(DataTable);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读