Click here to Skip to main content
15,894,646 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
Hi There,

I trying to read records from a text file and wants to insert those records into my database table after passing the column validations example customer Initials must be characters etc.
Please can any one provide me a sample code for this.
I have the following text file.

H|customer
D|101112|customer Initials|customer Surname|Address 1|Addres 2|Address 3|27123456789|Active
D|101113|customer Initials|customer Surname|Address 1|Addres 2|Address 3|27123456790|Active
D|101114|customer Initials|customer Surname|Address 1|Addres 2|Address 3|27123456791|Active
D|101115|customer Initials|customer Surname|Address 1|Addres 2|Address 3|27123456792|Active
D|101116|customer Initials|customer Surname|Address 1|Addres 2|Address 3|27123456793|Active
D|101117|customer Initials|customer Surname|Address 1|Addres 2|Address 3|27123456794|Active
D|101118|customer Initials|customer Surname|Address 1|Addres 2|Address 3|27123456795|Active
D|101119|customer Initials|customer Surname|Address 1|Addres 2|Address 3|27123456796|Active

Thanks in advance
Posted

No, we can't! We don't know what database you are using, what tables you have, what fields in the tables, etc..

What we can do is suggest:
1) Read the file:
string[] lines = File.ReadAllLines(path);

2) Loop through each line, and proccess it into components:
foreach (string line in lines)
   {
   string[] components = line.Split('|');
   ...
   }

3) Construct a database connection, and a command, and write your fragments. Assuming SQL Server:
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO myTable (myField1, myField2) VALUES (@MF1, @MF2)", con);
com.Parameters.AddWithValue("@MF1", components[0]);
com.Parameters.AddWithValue("@MF2", components[1]);
com.ExecuteNonQuery();

The rest is up to you!
 
Share this answer
 
see here[^]
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900