1

What's the easiest way to import a CSV into a database via web application?

UPDATE:

Small example of CSV:

stop_id, stop_name, stop_desc, stop_lat, stop_lon, zone_id, stop_url
TR, Trenton, , 40.2177778, -74.7550000, 6, 
LVTN, Levittown-Tullytown, , 40.1402778, -74.8169444, 5, 
BRST, Bristol, , 40.1047222, -74.8547222, 4, 
CROY, Croydon, , 40.0936111, -74.9066667, 4, 
EDGT, Eddington, , 40.0830556, -74.9336111, 4, 
CORN, Cornwells Heights, , 40.0716667, -74.9522222, 3, 
TORR, Torresdale, , 40.0544444, -74.9844444, 3, 
HOLM, Holmesburg Jct, , 40.0327778, -75.0236111, 2, 
John Saunders
  • 160,644
  • 26
  • 247
  • 397
balexander
  • 23,131
  • 14
  • 45
  • 68
  • possible duplicate of [How to read a csv file into a .net datatable](http://stackoverflow.com/questions/1050112/how-to-read-a-csv-file-into-a-net-datatable) – Rob Aug 26 '10 at 14:10
  • CSV stands for "Comma Separated Values", which is another way of saying "Comma Delimited". If your sure that's not the case for your text file, show us a sample of the content in your question =) You'll also need to be clearer by what you mean with "straight import", would writing a small windows console application be acceptable? – Rob Aug 26 '10 at 14:14
  • Oh true no your right haha. But the answer there looks like a web page insert rather then a straight import. Or am I still wrong? – balexander Aug 26 '10 at 14:15
  • @Rob Not sure never imported raw data into a database before. I guess whichever way is best. As it would take hours to do it by hand. – balexander Aug 26 '10 at 14:16
  • I've added an answer that's a start, let me know how much more detail you need =) – Rob Aug 26 '10 at 14:28

2 Answers2

1

If you take the Portable and Efficient Generic Parser for Flat Files and create a new Visual C# Console application that has a reference to it, the following code will load the contents of a CSV file into a DataTable:

using GenericParsing;
using System.Data;

namespace CsvToDataTable
{
    public class Program
    {
        static void Main(string[] args)
        {
            var pathOfCsvFile = @"C:\MyFile.csv";
            var adapter = new GenericParsing.GenericParserAdapter(pathOfCsvFile);
            DataTable data = adapter.GetDataTable();
        }
    }
}

The next step would be to save the data in data to your database server. This code assumes that the structure of the CSV file matches exactly that of a table called TableName in your database:

private static void SaveDataToDatabase(DataTable data)
{
    var connectionString = "CONNECTION STRING GOES HERE";
    var commandText = "INSERT INTO [databasename].[dbo].[TableName] " +
        "(stop_id, stop_name, stop_desc, stop_lat, stop_lon, zone_id, stop_url) " +
        "VALUES (@stop_id, @stop_name, @stop_desc, @stop_lat, @stop_lon, @zone_id, @stop_url)";

    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        foreach (DataRow row in data.Rows)
        {
            using (var command = new SqlCommand(commandText, connection))
            {
                command.Parameters.AddWithValue("@stop_id", row["stop_id"]);
                command.Parameters.AddWithValue("@stop_name", row["stop_name"]);
                command.Parameters.AddWithValue("@stop_desc", row["stop_desc"]);
                command.Parameters.AddWithValue("@stop_lat", row["stop_lat"]);
                command.Parameters.AddWithValue("@stop_lon", row["stop_lon"]);
                command.Parameters.AddWithValue("@zone_id", row["zone_id"]);
                command.Parameters.AddWithValue("@stop_url", row["stop_url"]);

                command.ExecuteNonQuery();
            }
        }
    }
}

You'd then want to add a call to SaveDataToDatabase in your Main method. I think there's enough code here for you to tweak it to suit your purpose.

Rob
  • 45,296
  • 24
  • 122
  • 150
  • @Rob could you please, if you don't mind. I am downloading that parser now. Also, I know this may sound stupid, but after I add the reference .dll file do I place the code above in a web form? If not what file type. – balexander Aug 26 '10 at 14:31
  • @Bry4n, this is for a "Console Application". You could do it in a WebForm if you wanted to though, the overall principal would be the same! =) – Rob Aug 26 '10 at 14:39
  • @Rob Is it easier to create a web application? I think my boss would ultimately ask for it in a web application haha. Thanks for all your help Rob. – balexander Aug 26 '10 at 14:40
  • @Bry4n, I've pasted in an example of how to get the data in the datatable into a table in a database. There are more elegant ways to do it, but this is pretty self-explanatory! =) – Rob Aug 26 '10 at 14:45
  • @Rob Okay I see. Do I still need the top part at all anymore? Also I am using DataSets and DataTableAdapters if that helps. – balexander Aug 26 '10 at 14:48
  • @Bry4n, You'll still need the top part to get the CSV file *into* a DataTable. I suggest you have a play around and try to get it working, there's more than enough code there now to do so =) – Rob Aug 26 '10 at 14:51
  • @Rob thank you! I will spend time figuring it out and teaching the rest myself. I hope I can figure it out! – balexander Aug 26 '10 at 14:55
  • @Bry4n, glad to help.... If you have any questions about specific bits, it'd probably be best to ask them as new questions, highlighting the specific bit that's causing you a problem =) Oh, and feel free to up-vote my answer, you can do that *as well* as accept it, and it'll get you a bit nearer to the "Civic Duty" badge ;) – Rob Aug 26 '10 at 14:58
  • @Rob I got further than expected. If you look in my recent questions I posted one that you may be able to help with. Thanks! – balexander Aug 26 '10 at 16:13
0

That's really going to depend on your situation. Is this an internal text file being loaded into SqlServer 2005 or later database (also internal)? If so, you can write an SSIS package (or, more simply, use SQL Server's "Import Data..." wizard) and it will just read it for you.

Is there reason to worry about unescaped commas (Say, a Name column with name formats in Last, First)? Then you'll need to compensate for that... (numerous question here on SO address this very issue).

Is the File not internal, that is, someone is uploading it and it needs to be read real-time? Then an SSIS package is still your best bet, and set up some code (Modern FTP Servers can often call executables or batch files) to kick off the SSIS package when the file arrives.

This is really a very broad kind of question, and without more detail, I'm not sure how specific the answers you're going to get will be...

AllenG
  • 8,112
  • 29
  • 40
  • I understand it was broad. Right now it will be internal but possibly grow to be online and have people just go and upload it to update the data. Which probably means I should take that route. I don't believe unescaped commas are an issue. – balexander Aug 26 '10 at 14:24