I am trying to import a .csv
file into a SQL Server database without the headers.
This code works fine, but with headers - how can skip the headers? What do
Just ignore the headers when you read the data from the file. Delete these lines:
string[] headerColumns = header.Split(',');
foreach (string headerColumn in headerColumns)
{
importedData.Columns.Add(headerColumn);
}
Can you remove the columns and use index instead? Of course, you'd need to know the position of each field within a file.
string line = "001,0000002226,01,2011/03/27,07:07,";
DataTable importedData = new DataTable();
DataRow importedRow = importedData.NewRow();
string[] fields = line.Split(',');
for (int i = 0; i < fields.Count(); i++)
{
importedRow[i] = fields[i];
}
using (SqlConnection conn = new SqlConnection("Data Source=HAIDER-PC\\SQLEXPRESS;Initial Catalog=mydatabase;Integrated Security=True"))
{
conn.Open();
foreach (DataRow importRow in importedData.Rows)
{
SqlCommand cmd = new SqlCommand("INSERT INTO imported_data (device_id,employee_id,status,date,time ) " +
"VALUES (@device_id,@employee_id,@status,@date,@time)", conn);
cmd.Parameters.AddWithValue("@device_id", importRow[0]);
cmd.Parameters.AddWithValue("@employee_id", importRow[1]);
cmd.Parameters.AddWithValue("@status", importRow[2]);
cmd.Parameters.AddWithValue("@date", importRow[4]);
cmd.Parameters.AddWithValue("@time", importRow[5]);
cmd.ExecuteNonQuery();
}
}