WGr*_*eau 4 sql-server excel vba
Excel问题:用户单击按钮,VBA解析输入文件,将数据放入电子表格中的单元格.然后,她将电子表格的副本邮寄给使用数据的人员.
我将用SSRS或ASP或Sharepoint替换它来显示SQL Server中的数据.
为了在不中断当前进程的情况下处理这个问题,我想让Excel VBA在每次向电子表格写入一行时,也通过存储过程将其插入SQL Server DB.
我可以让它将CSV中的行写入文件以便以后进行SSIS导入,但我宁愿直接进入数据库.
我知道如何在VB.Net中做到这一点,但我从未在VBA中写入数据(通常将数据读入记录集但不写入).
我更喜欢将值作为参数传递给存储过程,但如果必须的话,我可以为每一行生成较慢的INSERT命令.
从VBA,最容易使用的数据访问库是ADO.添加对"Microsoft ActiveX数据对象库"的引用,以便您可以使用ADODB.*对象.
要执行存储过程(在您的情况下将向表中添加记录),您可以执行以下操作:
...懒惰的方式(直接创建SQL语句,不使用Parameter对象;这很容易出现SQL注入攻击):
Public Sub AddFoo _
( _
strServer As String, _
strDatabase As String, _
strUsername As String, _
strPassword As String, _
lFooValue As Long _
)
' Build the connection string
Dim strConnectionString As String
strConnectionString = "Driver={SQL Server}" _
& ";Server=" & strServer _
& ";Database=" & strDatabase _
& ";UID=" & strUsername _
& ";PWD=" & strPassword
' Create & open the connection
Dim oConnection As Connection
Set oConnection = New Connection
oConnection.ConnectionString = strConnectionString
oConnection.Open
' Build the SQL to execute the stored procedure
Dim strSQL As String
strSQL = "EXEC AddFoo " & lFooValue
' Call the stored procedure
Dim oCommand As Command
Set oCommand = New Command
oCommand.CommandType = adCmdText
oCommand.CommandText = strSQL
oCommand.ActiveConnection = oConnection
oCommand.Execute
oConnection.Close
End Sub
Run Code Online (Sandbox Code Playgroud)
...或正确的方式(处理所有参数的编码,因此不容易出现SQL注入攻击 - 无论是故意的还是偶然的):
Public Sub AddFoo _
( _
strServer As String, _
strDatabase As String, _
strUsername As String, _
strPassword As String, _
lFooValue As Long _
)
' Build the connection string
Dim strConnectionString As String
strConnectionString = "Driver={SQL Server}" _
& ";Server=" & strServer _
& ";Database=" & strDatabase _
& ";UID=" & strUsername _
& ";PWD=" & strPassword
' Create & open the connection
Dim oConnection As Connection
Set oConnection = New Connection
oConnection.ConnectionString = strConnectionString
oConnection.Open
' Build the SQL to execute the stored procedure
Dim strSQL As String
strSQL = "EXEC AddFoo " & lFooValue
' Create the command object
Dim oCommand As Command
Set oCommand = New Command
oCommand.CommandType = adCmdStoredProc
oCommand.CommandText = "AddFoo"
' Create the parameter
Dim oParameter As Parameter
Set oParameter = oCommand.CreateParameter("foo", adParamInteger, adParamInput)
oParameter.Value = lFooValue
oCommand.Parameters.Add oParameter
' Execute the command
oCommand.ActiveConnection = oConnection
oCommand.Execute
oConnection.Close
End Sub
Run Code Online (Sandbox Code Playgroud)