简体   繁体   English

sqlbulkcopy-将字符串转换为DateTime时

[英]sqlbulkcopy - When converting string to DateTime

I am using this code to insert a csv file to my database: 我正在使用以下代码将csv文件插入到我的数据库中:

    private void InsertDataIntoSQLServerUsingSQLBulkCopy(DataTable csvFileData)
    {
        using (SqlConnection dbConnection = new SqlConnection(ConnectionString))
        {
            dbConnection.Open();
            using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
            {
                s.DestinationTableName = "tablename";
                foreach (var column in csvFileData.Columns)
                    s.ColumnMappings.Add(column.ToString(), column.ToString());
                s.WriteToServer(csvFileData);
            }
        }
    }


    private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
    {
        DataTable csvData = new DataTable();
        try
        {
            using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
            {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = true;
                string[] colFields = csvReader.ReadFields();
                foreach (string column in colFields)
                {
                    DataColumn datecolumn = new DataColumn(column);
                    datecolumn.AllowDBNull = true;
                    csvData.Columns.Add(datecolumn);

                }
                while (!csvReader.EndOfData)
                {
                    string[] fieldData = csvReader.ReadFields();

                    for (int i = 0; i < fieldData.Length; i++)
                    {
                        if (fieldData[i] == "")
                        {
                            fieldData[i] = null;
                        }
                    }
                    csvData.Rows.Add(fieldData);
                }
            }
        }

My database has temporary data in it. 我的数据库中有临时数据。 To test this code I copied fields with headers from SQL server and pasted it into an excel file. 为了测试此代码,我从SQL Server复制了带有标头的字段并将其粘贴到excel文件中。 I then saved the excel file to csv and ran the code. 然后,我将excel文件保存到csv并运行了代码。 It adds the data from the csv to the database perfectly! 它将csv中的数据完美地添加到数据库中!

I then tried running a csv file with similar values to my original csv file and its giving me a 'String to DateTime' Exception. 然后,我尝试运行具有与原始csv文件相似的值的csv文件,并且该文件给了我“日期时间的字符串”异常。 So I know something is up with the Dates and I know that the excel columns are in value of 'Date'. 所以我知道日期有问题,而且我知道excel列的值为“日期”。

Im really scratching my head with this one. 我真的很抓这个。 Any good way to parse columns with dates? 有什么好方法来解析带有日期的列?

I'm noticing a few issues with your code that could cause you some trouble. 我注意到您的代码存在一些问题,可能会给您带来一些麻烦。

  1. There is no schema validation of the CSV file. CSV文件没有架构验证。 You simple take any given CSV file and attempt to write it to the server using whatever column headers it has. 您只需简单地获取任何给定的CSV文件,然后尝试使用其具有的任何列标题将其写入服务器。
  2. When you create a DataColumn instance, the default column type will be System.String . 创建DataColumn实例时,默认列类型将为System.String This is probably causing your date issues. 这可能是导致您约会的问题。
  3. I don't see any transformation of the data in the CSV file. 我没有看到CSV文件中数据的任何转换。 If one of the fields in your database table is a datetime and you are attempting to bulk insert a System.String column you are going to run into issues. 如果数据库表中的字段之一是datetime并且您试图批量插入System.String列,则会遇到问题。

My suggestions would be the following: 我的建议如下:

  1. Perform schema validation on the CSV file so you know you are getting the input you expect. 在CSV文件上执行架构验证,以使您知道自己正在获得期望的输入。 This is two-fold: ensure the data is in the expected format and ensure the expected column headers exist. 这有两个方面:确保数据采用预期的格式,并确保预期的列标题存在。
  2. For the table that you bulk insert, create column types that are appropriate for your SQL tables. 对于您批量插入的表,创建适合您的SQL表的列类型。 Use the overload of the DataColumn constructor where you specify the column data type: new DataColumn("Name", typeof(DateTime)) 在指定列数据类型的地方使用DataColumn构造函数的重载: new DataColumn("Name", typeof(DateTime))
  3. Take the data you E xtracted from the CSV (all as strings) and T ransform it into the required format, then L oad it. 带您E会从CSV xtracted数据(所有字符串)和T ransform成需要的格式,那么L OAD它。

The operation you are doing is a very basic ETL . 您正在执行的操作是一个非常基本的ETL It appears you have the Extract and Load portion working, the thing you are missing is the Transform component. 看来您有“提取和加载”部分正在工作,而缺少的是“变换”组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM