Home > front end >  C# & SQL Server database : record Parallel.ForEach error
C# & SQL Server database : record Parallel.ForEach error

Time:08-11

I am trying to fill my SQL Server database with 3 different .txt files I accomplished this using regular for but it takes a long time. Then since the order does not matter (in my database) I tried to use Parallel.ForEach but I get this error error

Here is my code

using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;

namespace LogwithDataBase
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=LogsUploaded;Integrated Security=SSPI");

        void filldata()
        {
            SqlDataAdapter da = new SqlDataAdapter("Select *From LogsTable", con);
            DataSet ds = new DataSet();
            con.Open();

            da.Fill(ds, "LogsTable");

            dataGridView1.DataSource = ds.Tables["LogsTable"];
            dataGridView1.Columns[1].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss.fff";
            con.Close();
        }

        private void datab_connect_Click(object sender, EventArgs e)
        {
            con.Open();
            IEnumerable<string> lines1 = File.ReadLines(openFileDialog1.FileName); //HWLog

            Parallel.ForEach(lines1, line1 =>
            {
                string timeStmp = line1.Split('\t')[0];
                string atmIdd = line1.Split('\t')[1];
                string fileTyp = "HWLog";
                string evenTex = line1.Split('\t')[2];
                string query = "INSERT INTO LogsTable (timestampof_log,atmID,fileType,eventText) values (@timeStmp, @atmIdd, @fileTyp, @evenTex)";
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@timeStmp", DateTime.Parse(timeStmp));
                cmd.Parameters.AddWithValue("@atmIdd", atmIdd);
                cmd.Parameters.AddWithValue("@fileTyp", fileTyp);
                cmd.Parameters.AddWithValue("@evenTex", evenTex);
                cmd.ExecuteNonQuery();
            });

            IEnumerable<string> lines2 = File.ReadLines(openFileDialog2.FileName); //SWLog
            Parallel.ForEach(lines2, line2 =>
            {
                string timeStmp = line2.Split('\t')[0];
                string atmIdd = line2.Split('\t')[1];
                string fileTyp = "SWLog";
                string evenTex = line2.Split('\t')[2];
                string query = "INSERT INTO LogsTable (timestampof_log,atmID,fileType,eventText) values (@timeStmp, @atmIdd, @fileTyp, @evenTex)";
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@timeStmp", DateTime.Parse(timeStmp));
                cmd.Parameters.AddWithValue("@atmIdd", atmIdd);
                cmd.Parameters.AddWithValue("@fileTyp", fileTyp);
                cmd.Parameters.AddWithValue("@evenTex", evenTex);
                cmd.ExecuteNonQuery();
            });

            IEnumerable<string> lines3 = File.ReadLines(openFileDialog3.FileName); //JournalLog
            Parallel.ForEach(lines3, line3 =>
            {
                string timeStmp = line3.Split('\t')[0];
                string atmIdd = line3.Split('\t')[1];
                string fileTyp = "JournalLog";
                string evenTex = line3.Split('\t')[2];
                string query = "INSERT INTO LogsTable (timestampof_log, atmID, fileType, eventText) VALUES (@timeStmp, @atmIdd, @fileTyp, @evenTex)";

                SqlCommand cmd = new SqlCommand(query, con);

                cmd.Parameters.AddWithValue("@timeStmp", DateTime.Parse(timeStmp));
                cmd.Parameters.AddWithValue("@atmIdd", atmIdd);
                cmd.Parameters.AddWithValue("@fileTyp", fileTyp);
                cmd.Parameters.AddWithValue("@evenTex", evenTex);

                cmd.ExecuteNonQuery();
            });

            string querycb = "SELECT DISTINCT fileType FROM LogsTable"; //COMBOBOXA DATA ÇEKMEK
            SqlCommand cmdcb = new SqlCommand(querycb, con); //COMBOBOXA DATA ÇEKMEK
            SqlDataReader drcb = cmdcb.ExecuteReader(); //COMBOBOXA DATA ÇEKMEK
            List<string> list = new List<string>(); //COMBOBOXA DATA ÇEKMEK
            list.Add(""); //COMBOBOXA DATA ÇEKMEK

            while (drcb.Read())
            {
                list.Add(drcb["fileType"].ToString());
            }

            drcb.Close();

            comboBox1.DataSource = list; //COMBOBOXA DATA ÇEKMEK
            con.Close();

            filldata();
        }
    }
}    

I couldn't solve this problem and I don't want to go back to regular for

CodePudding user response:

In terms of performance i would suggest to use sqlbulkcopy Just fill a DataTable with all the lines and insert all at once, its much faster than make a single query for each line in the file thant could be really really long.

    public static void BulkInsert(IEnumerable<string> lines)
    {
        DataTable dt = new DataTable();
        dt.TableName = "LogsTable";
        
        dt.Columns.Add("timestampof_log");
        dt.Columns.Add("atmID");
        dt.Columns.Add("fileType");
        dt.Columns.Add("eventText");

        foreach (var line in lines)
        {
            string timeStmp = line.Split('\t')[0];
            string atmIdd = line.Split('\t')[1];
            string fileTyp = "JournalLog";
            string evenTex = line.Split('\t')[2];

            dt.Rows.Add(timeStmp, atmIdd, fileTyp, evenTex);

        }

        BulkInsert(dt);
    }

    public static void BulkInsert(DataTable table)
    {
        using (var bulkInsert = new SqlBulkCopy(ConnectionString))
        {
            bulkInsert.DestinationTableName = table.TableName;
            bulkInsert.WriteToServer(table);
        }
    }

CodePudding user response:

Simplest way - open sql connection in each parallel thread.

Parallel.Foreach SQL querying sometimes results in Connection more detailed here

  • Related