问题
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim val As String
val = Range("B5").Value
' Open the connection and execute.
conn.Open sConnString
Dim item As String
item = "INSERT INTO [IndustrialComp].[dbo].[Header]("
item = item & " [server_name] "
item = item & " )Values("
item = item & " '" & val & "')"
conn.Execute item
The above code inserts whatever vale is in B5 into a sql server 08 databse (industcomp) a table called header and a collumn named server_name.
I bascially want insert multiple values into this database..the three collumns are server_name, phys and virt.
e.g b5 insert into server_name....c5 insert into phys...d5 insert into virt.
Would I need to declare multiple strings or is there a way to basically list the values against the corrisponding collumns?
Thanks
回答1:
You could do it this way
'Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim val As String, val2 as string, val3 as string
val = Range("B5").Value
val2 = Range("C5").Value
val3 = Range("D5").Value
' Open the connection and execute.
conn.Open sConnString
Dim item As String
item = "INSERT INTO [IndustrialComp].[dbo].[Header]("
item = item & " [server_name], [phys], [virt] "
item = item & " )Values("
item = item & " '" & val & "', '" & val2 & "', '" & val3 & "')"
conn.Execute item
This is fine if you are in control of the input. If you are handing to a third party, be very careful of SQL injection.
A user could, for example, put the following in the B5 cell
','',''); DROP TABLE HEADER ; --
and you would be in trouble if the connection has rights.
Always sanitise user input in a situation like this and use parameterised SQL wherever possible.
Hope this helps.
来源:https://stackoverflow.com/questions/20190387/inserting-data-from-excel-into-a-db