Share via

Saving million rows into database

ankit goel 766 Reputation points
2023-07-06T07:42:22.0133333+00:00

i am using the below code to insert data into database using datagridview but found out that it is not a good approach to use for loop as my data is very huge (million rows)

 if (dataGridView1.Rows.Count > 1)
        {

            for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
            {

                string col1 = dataGridView1.Rows[i].Cells[0].Value.ToString();

                string col2 = dataGridView1.Rows[i].Cells[1].Value.ToString();

                string col3 = dataGridView1.Rows[i].Cells[2].Value.ToString();

                string col4 = dataGridView1.Rows[i].Cells[3].Value.ToString();

                string col5 = dataGridView1.Rows[i].Cells[4].Value.ToString();

                using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectstring"].ConnectionString))
                {

                    string insert = "INSERT INTO InvoiceItems(SNo,Quantity,Rate,Description,Total) VALUES (@SNo,@Quantity,@Rate,@Description,@Total)";

                    con.Open();

                    SqlCommand cmd = new SqlCommand(insert, con);
                   // so on 

Please suggest me a faster and memory efficient approach which can save data much quicker into database

Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

Karen Payne MVP 35,606 Reputation points Volunteer Moderator
2023-07-06T19:10:42.9233333+00:00

Load the DataGridView with a DataTable than use (if SQL-Server) SqlBulkCopy, see example.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.