The following program illustrates how to import data from students.csv file into the students table in the elearning database:
In this program, we use an external package for reading a CSV file called CsvHelper. You can install the CsvHelper package by running the following command in the Package Manager Console:
Define a Studentrecord that includes the following fields: FirstName, LastName, Email, and RegistrationDate:
Defining ReadStudentsFromCSV() method
The ReadStudentsFromCSV() method reads data from a CSV file specified by a filePath and returns an enumerable sequence of Student records.
How it works.
First, create a StreamReader from the CSV file specified by the filePath. The using statement ensures that the StreamReader is properly closed:
Second, create a CsvReader to parse the CSV data. The CultureInfo.InvariantCulture ensures consistent parsing across different locales:
Third, read the heading line from a CSV file, which advances the reader to the next line in the CSV file:
Fourth, read the header row of the CSV file to map the column names to fields:
Fifth, start a loop that iterates over each line in the CSV file. The Read() method reads the next line from the CSV file and returns true if successful, or false if there are no more lines:
Sixth, retrieve the values of the columns of the CSV file:
Finally, return a new Student record for each row in the CSV file. The yield return returns multiple Student records iteratively without loading them all in memory:
Defining Main() method
First, declare a variable csvFilePath and initialize it with the path to the CSV file:
Next, declare a variable sql and initialize it with an SQL INSERT statement:
Then, get a connection string from the appsettings.json file using the ConfigurationHelper class:
After that, create a data source that represents the PostgreSQL database:
Finally, iterate over each Student record list returned by the ReadStudentsFromCSV() method and execute the INSERT statement to insert the new row into the students table:
Verify the inserts
First, open a terminal and connect to the elearning database using the ed user:
It’ll prompt you to enter a password for the ed user. Input the valid password and press Enter to connect to the PostgreSQL.
Second, query data from the students table:
Output:
The output indicates that the program has successfully imported 10 rows from the the students.csv file into the students table.
Summary
Utilize the CsvHelper package to read data from a CSV file.
Call the ExecuteNonQueryAsync() method of the NpgsqlCommand object to execute an SQL INSERT statement to load data from a CSV file into a table in the SQLite database.