【问题标题】:SQL BulkCopy doesn't insert into databaseSQL BulkCopy 不插入数据库
【发布时间】:2014-07-22 18:16:34
【问题描述】:

我的大部分应用程序都使用 LinqToSQL,但我需要从文件上传一些数据,从而插入大量数据。

这里有一个数据列表,我正在尝试插入它。我转换为表格(从列映射中省略了标识 MeterDataId 字段)。一切似乎都正常,但数据没有被提交。没有报告异常。

我检查了表格,它确实包含三个字段的数据。

我应该以某种方式设置 ID 字段吗?

谢谢

        SqlConnection SqlConnection = null;
        try {
            string cons = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"D:\\Visual Studio Projects\\SEMS\\SEMS\\bin\\Debug\\DataCore.mdf\";Integrated Security=True";

            SqlConnection = new SqlConnection(cons);
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }

        Type t = typeof(MeterData);

        var tableAttribute = (TableAttribute)t.GetCustomAttributes(
            typeof(TableAttribute), false).Single();

        var bulkCopy = new SqlBulkCopy(SqlConnection) {
            DestinationTableName = tableAttribute.Name
        };

        List<PropertyInfo> properties = new List<PropertyInfo>();

        properties.Add(t.GetProperty("DateTime"));
        properties.Add(t.GetProperty("Value"));
        properties.Add(t.GetProperty("Difference"));

        var table = new DataTable();

        foreach (var property in properties) {
            Type propertyType = property.PropertyType;
            if (propertyType.IsGenericType &&
                propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) {
                propertyType = Nullable.GetUnderlyingType(propertyType);
            }

            // set the SqlBulkCopy column mappings.
            table.Columns.Add(new DataColumn(property.Name, propertyType));
            var clrPropertyName = property.Name;
            var tableColumnName = property.Name;
            bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(clrPropertyName, tableColumnName));
        }

        // Add all our entities to our data table
        foreach (var entity in insertMeterDatas) {
            var e = entity;
            table.Rows.Add(properties.Select(property => GetPropertyValue(property.GetValue(e, null))).ToArray());
        }

        bulkCopy.WriteToServer(table);

        SqlConnection.Close();

【问题讨论】:

  • 你应该用using打开sql连接,然后你就不需要清理连接了。它将自动完成。此外,如果出现故障,连接将不会按照您现在编写代码的方式正确关闭。看看它,using 很棒!

标签: c# sql sql-server bulkinsert


【解决方案1】:
   string cs = DataContext.Connection.ConnectionString;

更新了连接字符串,现在好像可以用了!

编辑这不是诀窍。我发现处理 Linq DataContext 是可行的,但这搞砸了其他一切。

解决方案:将 DataContext.Connection (Cast to SQLConnection) 与 BulkInsert 一起使用。然后它使用已经打开的sql连接,现在似乎工作正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2020-05-22
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多