2013-11-25 117 views
0
' 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 

上述代碼插入任何谷是在B5到SQL服務器08 DATABSE(industcomp)的表被稱爲報頭和名爲server_name collumn。從EXCEL將數據插入到DB

我基本上想要插入多個值到這個數據庫..三個collumns是server_name,phys和virt。

例如b5插入server_name .... c5插入物理... d5插入到virt中。

我需要聲明多個字符串還是有辦法基本列出值與相應的collumns列表?

感謝

回答

0

你可以這樣

'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 

,如果你輸入的控制這很好做。如果您要交給第三方,請注意SQL注入。

一個用戶可以,例如,把下面的B5細胞

」, '', ''); DROP TABLE HEADER; -

如果連接有權限,您將遇到麻煩。

在這種情況下總是要處理用戶輸入,並儘可能使用參數化的SQL。

希望這會有所幫助。

+0

太好了!感謝您的幫助 – user3013325