How to .Net do I import values ​​from CSV in the format I want to use OleDB?

I have a CSV file in which there is a column containing rows that look like integers. That is, they should be treated as strings, but since they are numbers, they appear to be imported as integers (discarding leading zeros).

Sample data:

  • 0000000000079
  • 0000999000012
  • 0001002000005
  • 0004100000007

The problem that I see is that the last sample data points to DBNull.Value. I assume this is because OleDB treats this column as an integer (data points also pass without their leading zeros), and 0004100000007 is greater than the largest integer value.

Is it possible to say "column [0] is a string, do not read it as a whole"? When reading data?

The code I use is:

OleDbConnection dbConn = new OleDbConnection(SourceConnectionString);
OleDbCommand dbCommand = new OleDbCommand("SELECT * FROM test.csv", dbConn);
dbConn.Open();
OleDbDataReader dbReader = dbCommand.ExecuteReader();

while (dbReader.Read())
{
    if (dbReader[0] != DBNull.Value)
    {
         // do some work
    }
}
+3
source share
5 answers

Try using the GetString () method in the reader when you need to read a column as a string:

string myStringValue = reader.GetString(0);
+3
source

Do you have control over the export process? If so, can the data be exported to CSV with quotes around string elements?

If this is one of the tasks, simply import the file into a predefined SQL table using Integration Services, but I suspect this will be a recurring task.

+1
source

CSV-? , , . , ...

0

Source: https://habr.com/ru/post/1698723/


All Articles