Friday, March 23, 2012

Saving Arraylist to a Database

I have 3 strings delimitted by a * character that I would like to save to a database. Each string will always have the same number of elements.

strUserID = "1*2*3"

strCompanyID="12931*12937*12945"

strCompanyName="International Business Machines, Inc*Ford Motor Company*Delta Airlines"

What I need to do is to save each record like this

INSERT INTO tableA (UserID, CompanyID, CompanyName) VALUES (1, 12931, 'International Business Machines, Inc')

INSERT INTO tableA (UserID, CompanyID, CompanyName) VALUES (2, 12937, 'Ford Motor Company')

INSERT INTO tableA (UserID, CompanyID, CompanyName) VALUES (3, 12945, 'Delta Airlines')

I've done something like this before with a single string, but don't know how to handle 3 of them.

Dim strAlerts As String() = Nothing
strAlerts = values.Split(",")
Dim s As String
For Each s In strAlerts
SqlText = "INSERT INTO tableA (UserID, CompanyID, CompanyName) VALUES (" & lblUserID.Text & ", '" & lblCompanyID.Text & "','" & s & "')"
cmd = New SqlCommand(SqlText, strSQLConn)
cmd.ExecuteNonQuery()
Next s

Thanks for any help

I am just not clear on one thing, why you are using Labels in Insert statement. I hope you are looking for something like this :

Dim

arrUserID()AsString = strUserID.Split("*")Dim arrCompanyID()AsString = strCompanyID.Split("*")Dim arrCompanyName()AsString = strCompanyName.Split("*")Dim iAsIntegerDim SqlTextAsString =""For i = 0To 2

SqlText =

"INSERT INTO tableA (UserID, CompanyID, CompanyName) VALUES (" & arrUserID(i) &", '" & arrCompanyID(i) &"','" & arrCompanyName(i) &"')"

cmd =

New SqlCommand(SqlText, strSQLConn)

cmd.ExecuteNonQuery()

Next

Hope this helps
Cheers
Ritesh|||

Yes, this is exactly what I'm looking for. Thanks.

The only line that will not work is

For i = 0To 2

There could be any number of elements (not just 2) in the arrays so it can't be hard code at 2. How do I get the length of the arrays?

Thanks

|||Hey...I guess you said "Each string will always have the same number of elements."
Anyways...you can get the array length arrCompanyID.Length (for i = 0 to arrCompanyID.Length )

Ritesh|||Let me know, incase this thing doesnt work for you :)|||

Thank you Ritish. You're answer helped me immensely and I marked it as the answer.

I have another problem related to this same array if you happen to have any suggestionsSmile

http://forums.asp.net/thread/1672057.aspx

No comments:

Post a Comment