2

I have this project:

  1. Import a .txt file
  2. Connect to a SQL Server database
  3. Transfer all data into the database

The text file is divided by tab in four fields so as the database.

I've done the first step using a rich text box and saving all the data on a string. My idea is to split the string every line and save it on an array but then: How do I split every row so I can save the fields properly? How do I connect a database on SQL Server to my project on C#?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hazael Estrella
  • 31
  • 1
  • 2
  • 7

5 Answers5

4

Let's tackle this one step at a time...

Getting the data:


Get the text file into a string variable.
string readText = File.ReadAllText("path to my file.txt");

More on this here

Now that we have it in a string we can parse it

List<string> listStrLineElements = List<string> listStrLineElements = line.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).ToList();// You need using System.Linq at the top.

More options for splitting at a new line can be found here

Now, you need to split each element into its own row; you said you had it tab delimited which is good (something like comma seperated (CSV) is more common modernly, but tabs will work!)... For that we can do something like this:

List<string> rowList = listStrLineElements.SelectMany(s => s.Split('\t')).ToList();// The \t is an *escape character* meaning tab.

now, you need something like a loop to go through each one of these entries and insert it into the database, which means we now need our database connection...

Connecting to the database


Code Projects (another helpful site) has this tutorial on making a SQL connection from C#; below is a code summary (please read the article, this website is not here to have people write/find code on your behalf!)

Make sure you are using the SQL namespace...

using System.Data.SqlClient;

    private void sqlCon(List<string> x)
    {
        //Replace with your server credentials/info
        SqlConnection myConnection = new SqlConnection("user id=username;" +"password=password;server=serverurl;" +"Trusted_Connection=yes;" +"database=database; " + "connection timeout=30");
        try
        {
            myConnection.Open();
            for (int i = 0; i <= x.Count -4; i += 4)//Implement by 3...
            {
                //Replace table_name with your table name, and Column1 with your column names (replace for all).
                SqlCommand myCommand = new SqlCommand("INSERT INTO table_name (Column1, Column2, Column3, Column4) " +
                                     String.Format("Values ('{0}','{1}','{2}','{3}')", x[i], x[i + 1], x[i + 2], x[i + 3]), myConnection);
                myCommand.ExecuteNonQuery();
            }

        }
        catch (Exception e){Console.WriteLine(e.ToString());}
        try{myConnection.Close();}
        catch (Exception e){Console.WriteLine(e.ToString());}
    }

Note, you may very likely have to change/edit my loop; the logic behind it is to implement i by 4 so you can read each of your columns, so the columns Count (number of entries) must be 4 less so you don't get an index out of bounds (typing this all in notepad I'm not sure if I got all the logic right, but again, if it's wrong that is something you will have to fix, we don't just write code for people).

PLEASE NOTE!

things like string.format() leave you open for an SQL injection, you really should lookup SQL parameters, but this will get the job done. Here are some posts that I consider a must read:

Preventing SQL Injections in C#

What is an SQL Injection (W3-schools)

Community
  • 1
  • 1
Steve Byrne
  • 1,320
  • 1
  • 16
  • 29
  • 1
    Thank you for the big help. Just a thing: The for loop must be "i <= x.Count" or it'll never save the last entry, took me a while to fix that. Also, at first the connection "failed". It was connecting but wasn't saving anything. I used " Server = (local);" + "Database=name;" + "Trusted_Connection=yes;" with all the caps and semicolons. Plus, no user or character, the blog you sent me to said that wasn't necessary when using a trusted connection and it was right. Thanks again for leading me in the right way. – Hazael Estrella Sep 29 '16 at 23:12
0

You should review the MSDN documentation about this subject here This will provide some details on how to connect to a SQL server database.

Soul
  • 67
  • 6
0

To connect to the database, you'll need a connection string with all the info inside the app.config file. Once you connect to the db, there should be no problem to add a new row or even update one from inside your code. Simply build a Query you where you enter the string data for each column of the new row !

There is a ton of documentation on how to build SQL queries and how to connect to a database on the Microsoft website, give it a look :)

Picnic8
  • 363
  • 2
  • 12
0

You could try using BCP from command line. This makes a bunch of assumptions about what permissions you have, and how you access the database, but basically you can call this on the database server (its a hidden feature) or you can copy the file locally:

https://msdn.microsoft.com/en-us/library/ms162802.aspx

BCP.exe .. in -S -U -P -c -t

-c is "character format" -t is field terminator - leave blank for TAB

-U and -P can be replaced with -T if it is a trusted connection.

Some advice: These things are always better handled by importing to a staging table, making any changes you need, and then having a SQL function handle the transfer to the production table. This way you can make sure you don't blow away data by accident.

Nick Pfitzner
  • 206
  • 2
  • 9
0

I would advise making use of Lists and datatable in this scenarios. The use of lists is clean when compared to array and the same applies to operations on the database using data tables. You could refer this post on stackoverflow to retrieve data from a text file into a data table. This post could also help

Hope this helps..

Viragos
  • 561
  • 6
  • 15
akhila
  • 720
  • 2
  • 7
  • 17