i want to parse a CSV file, store it in a list then insert values from that list to a database . Here is the sample of my code. I'm still learning so if it is not clear then i will explain further. But the idea is to parse the csv file, row by row, and then insert each row in my database. Thank you in advance.
public class SKU : List<string[]>
{
public string SKU_ID { get; set; }
public string SKU_Name { get; set; }
public string Code { get; set; }
public string Product_Name { get; set; }
public string DistributionCenter_Name { get; set; }
internal static SKU ParseRow(string row)
{
var columns = row.Split(';');
return new SKU()
{
SKU_ID = columns[0],
SKU_Name = columns[1],
Code = columns[2],
Product_Name = columns[3],
DistributionCenter_Name = columns[4],
};
}
}
In the script i named each column like in the csv file and in my database.
My main is as following
class Programm
{
static void Main(string[] args)
{
var sku_info = ProcessCSV("skutest1.csv");
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"...";
foreach (var information in sku_info)
{
using SqlConnection connection = new SqlConnection(conn.ConnectionString);
string commandString = ("INSERT INTO SKU VALUES ('" + information.SKU_ID + " "+information.SKU_Name+" "+information.Code+" "+information.Product_Name+" "+information.DistributionCenter_Name+"')");
conn.Open();
SqlTransaction transaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand(commandString, conn, transaction);
cmd.ExecuteNonQuery();
transaction.Commit();
}
Console.ReadKey();
}
private static List<SKU> ProcessCSV(string path)
{
return File.ReadAllLines("C:/.../skutest1.csv").Where(row => row.Length > 0).Select(SKU.ParseRow).ToList();
}
}