Smail Smail - 1 month ago 10
MySQL Question

C# - Insert first colum from text file to database

I would like to read from text file and insert his first column as row in database.

This is the text file how it looks like:

1264311 | SMS_DR | DELIVERED
373414 | SMS_DR | EXPIRED
418 | SMS_DR | UNDELIVERABLE
1628984 | SMS_MT |


I want to get only the first column with integer values and insert them in my database as a row to have this:

DELIVERED EXPIRED UNDELIVERABLE BLABLA
1264311 373414 418 1628984


When i run my code it inserts all 4 lines, this my code:

sr1 = new StreamReader("C:\\Users\\adamoui\\Desktop\\Statjbm_20161009.txt");

string[] allLines1 = File.ReadAllLines("C:\\Users\\adamoui\\Desktop\\Statjbm_20161009.txt");

for (int i = 0; i < allLines1.Length; i++)
{
string[] column = allLines1[i].Split(new char[] { '|' });
SqlCommand cmdJBM = new SqlCommand("INSERT INTO dbo.StatJBM_NEW (Noeud, Total_MT, Date, DELIVERED, EXPIRED, UNDELIVERABLE) VALUES (@Noeud, @Total_MT, @Date, @DELIVERED, @EXPIRED, @UNDELIVERABLE)", con);
cmdJBM.Parameters.AddWithValue("@Noeud", "JBM");
cmdJBM.Parameters.AddWithValue("@DELIVERED", column[0]);
cmdJBM.Parameters.AddWithValue("@EXPIRED", column[0]);
cmdJBM.Parameters.AddWithValue("@UNDELIVERABLE", column[0]);
cmdJBM.Parameters.AddWithValue("@Total_MT", column[0]);
cmdJBM.Parameters.AddWithValue("@Date", DateTime.Now.AddDays(-1));
cmdJBM.ExecuteNonQuery();
}
con.Close();


Result:

enter image description here

Answer

You need something of this sort:

var delivered = allLines[0].Split(new char[] { '|' })[0];
var expired = allLines[1].Split(new char[] { '|' })[0];
var undeliverable = allLines[2].Split(new char[] { '|' })[0];
....
cmdJBM.Parameters.AddWithValue("@DELIVERED", delivered);
cmdJBM.Parameters.AddWithValue("@EXPIRED", expired);
cmdJBM.Parameters.AddWithValue("@UNDELIVERABLE", undeliverable);
Comments