Inserting an array into a table

Thread Solved

Join Date: Jan 2008
Posts: 54
Reputation: Xessa is an unknown quantity at this point 
Solved Threads: 0
Xessa Xessa is offline Offline
Junior Poster in Training

Inserting an array into a table

 
0
  #1
Jun 5th, 2009
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.
Reply With Quote Quick reply to this message  
Join Date: Oct 2005
Posts: 93
Reputation: humbug is an unknown quantity at this point 
Solved Threads: 13
humbug's Avatar
humbug humbug is offline Offline
Junior Poster in Training

Re: Inserting an array into a table

 
0
  #2
Jun 7th, 2009
You can use a for loop to operate on each element of the array. I'm assuming it's a one (meaningful) columned table.
  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:
  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
"If your not having fun, your doing something wrong." - Humbug
★ Did I help you out? Did I piss you off? Add to my reputation!
The Gabriel Method is a great book for losing weight and keeping healthy - I know Jon Gabriel Personally.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC