Excel 问题:用户单击按钮,VBA 解析输入文件,将数据放入电子表格的单元格中。然后,她将电子表格的副本邮寄给处理数据的人员。
我将用 SSRS 或 ASP 或 Sharepoint 替换它,显示来自 SQL Server 的数据。
为了在不中断当前进程的情况下完成此操作,我希望使用 Excel VBA,每次向电子表格写入一行时,还通过存储过程将其插入 SQL Server 数据库。
我可以让它将 CSV 中的行写入文件以供以后 SSIS 导入,但我宁愿直接转到数据库。
我知道如何在 VB.Net 中执行此操作,但我从未在 VBA 中编写数据(经常将数据读到记录集中但不写入)。
我更愿意将值作为参数传递给存储过程,但如果必须的话,我可以为每行生成较慢的 INSERT 命令。
最佳答案
对于 VBA,最容易使用的数据访问库是 ADO。添加对“Microsoft ActiveX 数据对象库”的引用,以便您可以使用 ADODB.* 对象。
要执行存储过程(在您的情况下将向表中添加一条记录),您可以这样做:
...懒惰的方式(直接创建 SQL 语句,而不使用参数对象;这很容易受到 SQL 注入(inject)攻击):
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
...或者正确的方法(处理所有参数的编码,因此不容易受到 SQL 注入(inject)攻击 - 无论是有意还是无意):
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
关于sql-server - Excel VBA 到 SQL Server(无需 SSIS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1690622/