Click here to Skip to main content
14,638,900 members
Rate this:
Please Sign up or sign in to vote.
See more:
How to read text file data in sql server 2008???

I have a one text file and data insert into database.
Posted
Updated 11-Nov-19 23:27pm
v2
Comments
Richard MacCutchan 11-Oct-13 3:19am
   
With notepad.
Rate this:
Please Sign up or sign in to vote.

Solution 1

Hello,

You can use BULK INSERT[^] for this.

e.g.
BULK INSERT csv_test
FROM 'F:\csv_data.txt'
WITH
(
    FIELDTERMINATOR = ',',
    ROWTERMINATOR = '\n'
)
GO

The above examples inserts data from a CSV text file into SQL server table.

Regards,
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Assuming that you mean to read the file in C# and insert it into your SQL Db (otherwise why mention C# in the tags?) then exactly how you do it depends on what kind of column you have created in SQL.
If it is VARCHAR:
string myFileString = File.ReadAllText(path);
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("INSERT INTO myTable (myColumn) VALUES (@TEXT)", con))
        {
        com.Parameters.AddWithValue("@TEXT", myFileString);
        com.ExecuteNonQuery();
        }
    }
If it is VARBINARY:
byte[] myFiledata = File.ReadAllBytes(path);
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("INSERT INTO myTable (myColumn) VALUES (@DATA)", con))
        {
        com.Parameters.AddWithValue("@DATA", myFileData);
        com.ExecuteNonQuery();
        }
    }
   
Comments
Prasad Khandekar 11-Oct-13 5:26am
   
My 5+, I totally missed C# tag.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100