943,712 Members | Top Members by Rank

Ad:
Jun 5th, 2009
0

Inserting an array into a table

Expand Post »
I want to insert an array into a table.

Each array element is a row in the table. How can I achieve my goal?



I don't want to use

 VALUES x1,x2,x3,x4 ......
Last edited by Xessa; Jun 5th, 2009 at 6:12 am.
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
Xessa is offline Offline
58 posts
since Jan 2008
Jun 7th, 2009
0

Re: Inserting an array into a table

You can use a for loop to operate on each element of the array. I'm assuming it's a one (meaningful) columned table.
c++ Syntax (Toggle Plain Text)
  1. //len is length of array
  2. for (i=0; 0<len; i++){
  3. //create SQL statement
  4. sql="INSERT INTO table (row1) VALUES " . array[i];
  5. //[execute sql here]
  6. }

Alternatively, you could do it like so, if it will work with your version of SQL:
c++ Syntax (Toggle Plain Text)
  1. //all inserts are done in the one SQL statement
  2.  
  3. int len = //length of array
  4. //the start of the statement. The first element is done here because
  5. //one less comma is required then the number of elements
  6. string sql = "INSERT INTO table (row1) VALUES (" . array[0];
  7. for (int i=1; 0<len; i++){
  8. //create SQL statement
  9. sql .= "), VALUES (" . array[i];
  10. }
  11. sql .= ");";
  12. //[execute sql here]

http://en.wikipedia.org/wiki/Insert_(SQL)
Last edited by humbug; Jun 7th, 2009 at 12:27 am. Reason: found better solution
Reputation Points: 20
Solved Threads: 13
Junior Poster in Training
humbug is offline Offline
93 posts
since Oct 2005

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Database Design Forum Timeline: Database design for child care
Next Thread in Database Design Forum Timeline: Pushing projection below a selection





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC