• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 423
  • Last Modified:

ArrayList saved to SQL database?


I have a Session arraylist that I need to write each row into an SQL database:

ArrayList items = (ArrayList)Session["mycart"];

Q. How do you save an ArrayList to an SQL database?
0
kvnsdr
Asked:
kvnsdr
  • 2
1 Solution
 
TheAvengerCommented:
The best would be if you make several tables in the database: order, item. The order will be connected with the current user (one user can have multiple orders), item is connected to an order (one order can have multiple items). In the items table you will save all the properties of the item. Then you can go over the array list and save every item in the items table using an SqlCommand or an SqlDataAdapter
0
 
kvnsdrAuthor Commented:
So a Session DataSet is a better choice than an ArrayList?
0
 
TheAvengerCommented:
Yes and no. The dataset will take more memory for every user on your site but will give you a flexible way to save in the database. So you have to chose: either use more memory and develop easily or use less memory and make transformations before you save the data
0
 
djbrown79Commented:
I'm going to make the following assumptions about the environment/design:

- Each item in the ArrayList() is meant to be a row in the database
- There is a stored procedure that will be called to actually perform the insert
- Each item in the ArrayList() is an object containing something on the order of fields (i.e., multiple values of some kind)

The psuedo-code for accomplishing this would look something like:

using( SqlConnection Connection = GetSqlConnection() )
{
    SqlCommand Command = new SqlCommand( StoredProcedureName );
    Command.CommandType = CommandType.StoredProc;

    SqlParameterCollection Parameters = Command.Parameters;
    Parameters.Add( Field1 );
    Parameters.Add( Field2 );
    Parameters.Add( Field3 );
    // --- etc. ----
 
    foreach( LineItem in TheArrayList )
    {
        Parameters[ Field1 ] = LineItem.Value1;
        Parameters[ Field2 ] = LineItem.Value2;
        Parameters[ Field3 ] = LineItem.Value3;
        // --- etc. ---

        Command.ExecuteNonQuery();
    }
}

There are a few more efficiencies that could be applied, but they will greatly increase the complexity. Odds are that it just wouldn't be worth it as there probably would be no perceivable performance impact.

Let me know if any of my assumptions are incorrect and I will update this response accordingly.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now