0

可能重复:
将 C# 中的 nvarchar 值转换为 Sql 中的等效日期/时间

我从 txt 文件中读取的数据包含不同的列。在插入数据库之前,我需要将一列的类型转换为日期/时间

SqlBulkCopy bc = new SqlBulkCopy(Consql.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "name";
bc.ColumnMappings.Add(dt.Columns[0].ColumnName, "IDATE");
bc.ColumnMappings.Add(dt.Columns[1].ColumnName, "ITIME");
bc.ColumnMappings.Add(dt.Columns[2].ColumnName, "TECHID");
bc.ColumnMappings.Add(dt.Columns[5].ColumnName, "CNTRC");
bc.BatchSize = dt.Rows.Count;
Consql.Open();
4

1 回答 1

0

我认为要使用 SqlBulkCopy 你需要实现 IDataReader 接口。实现它,您可以将源文件中的值转换为所需的类型。

您的自定义阅读器可能如下所示

 public class Reader : IDataReader
    {
        readonly StreamReader _streamReader;

        readonly Func<string, object>[] _convertTable;
        readonly Func<string, bool>[] _constraintsTable;

        string[] _currentLineValues;
        string _currentLine;

        //Constructing reader you can specify your converters     
        public Reader(string filepath, Func<string, bool>[] constraintsTable, Func<string, object>[] convertTable)
        {
            _constraintsTable = constraintsTable;
            _convertTable = convertTable;
            _streamReader = new StreamReader(filepath);

            _currentLine = null;
            _currentLineValues = null;
        }


        public object GetValue(int i)
        {
            try
            {
                return _convertTable[i](_currentLineValues[i]);
            }
            catch (Exception)
            {
                return null;
            }
        }


        public bool Read()
        {
            if (_streamReader.EndOfStream) return false;

            _currentLine = _streamReader.ReadLine();


            _currentLineValues = _currentLine.Split(/*any column splitter*/);

            var invalidRow = false;
            for (int i = 0; i < _currentLineValues.Length; i++)
            {
                if (!_constraintsTable[i](_currentLineValues[i]))
                {
                    invalidRow = true;
                    break;
                }
            }

            return !invalidRow || Read();
        }



//other methods...
}

您可以像这样使用它(将源列之一转换为 DateTime):

static void Main(string[] args)
        {
            // Create Reader
            var reader = GetReader();

            // DB connection string
            var connectionString = @"Server={blah};initial catalog={blah-blah};Integrated Security=true";     

            using (var loader = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.Default))
            {
                loader.ColumnMappings.Add(0, 2);
                loader.ColumnMappings.Add(1, 1);
                loader.ColumnMappings.Add(2, 3);
                loader.ColumnMappings.Add(3, 4);

                loader.DestinationTableName = "Customers";
                loader.WriteToServer(reader); 

                Console.WriteLine("Done!");
            }

            Console.ReadLine();
        }

        static IDataReader GetReader()
        {
            var sourceFilepath = "sqlbulktest.txt";
            //our converters!
            var convertTable = GetConvertTable();

            var constraintsTable = GetConstraintsTable();

            var reader = new Reader(sourceFilepath, constraintsTable, convertTable);
            return reader;
        }

        static Func<string, bool>[] GetConstraintsTable()
        {
            var constraintsTable = new Func<string, bool>[4];

            constraintsTable[0] = x => !string.IsNullOrEmpty(x);
            constraintsTable[1] = constraintsTable[0];
            constraintsTable[2] = x => true;
            constraintsTable[3] = x => true;
            return constraintsTable;
        }

        static Func<string, object>[] GetConvertTable()
        {
            var convertTable = new Func<object, object>[4];

            convertTable[0] = x => x;


            convertTable[1] = x => x;


            // Convert to DateTime from specific format!
            convertTable[2] = x =>
                              {
                                  DateTime datetime;
                                  if (DateTime.TryParseExact(x.ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture,
                                        DateTimeStyles.None, out datetime))
                                  {
                                      return datetime;
                                  }
                                  return null;
                              };     

            convertTable[3] = x => Convert.ToInt32(x);

            return convertTable;
        }
于 2012-05-12T20:33:50.297 回答