【发布时间】:2016-02-05 18:58:40
【问题描述】:
我正在使用以下代码:
Public Sub Add_File(Update_Table As Integer)
Dim Fpath = My.Settings.Database_Connection_String
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True
fd.Multiselect = True
If fd.ShowDialog() = DialogResult.OK Then
Dim FileRow
Try
FileRow = Form1.Projects_DGV.SelectedCells.Item(0).RowIndex
Catch ex As Exception
FileRow = 0
End Try
Dim FileX = Form1.Projects_DGV.Item(0, FileRow).Value
For Each file As String In fd.FileNames
strFileName = file
' this code requires that your project have the following COM Reference:
' Microsoft Office 14.0 Access Database Engine Object Library
Dim dbe As New Microsoft.Office.Interop.Access.Dao.DBEngine
Dim db As Microsoft.Office.Interop.Access.Dao.Database = dbe.OpenDatabase(My.Settings.Database_Location)
Dim rstRecord As Microsoft.Office.Interop.Access.Dao.Recordset = db.OpenRecordset( _
"SELECT * FROM [Projects] WHERE [Project ID]=" & FileX, _
Microsoft.Office.Interop.Access.Dao.RecordsetTypeEnum.dbOpenDynaset)
rstRecord.Edit()
Dim rstAttachments As Microsoft.Office.Interop.Access.Dao.Recordset2
If Update_Table = 1 Then
rstAttachments = rstRecord.Fields("Invoice").Value
ElseIf Update_Table = 2 Then
rstAttachments = rstRecord.Fields("Software Handover").Value
ElseIf Update_Table = 3 Then
rstAttachments = rstRecord.Fields("Other Documents").Value
ElseIf Update_Table = 4 Then
rstAttachments = rstRecord.Fields("Project Documents").Value
End If
rstAttachments.AddNew()
Dim AttachmentData As Microsoft.Office.Interop.Access.Dao.Field2 = rstAttachments.Fields("FileData")
AttachmentData.LoadFromFile(strFileName)
rstAttachments.Update()
rstAttachments.Close()
rstRecord.Update()
rstRecord.Close()
db.Close()
Next
setupdatagrids()
End If
End Sub
此代码应该允许我将文件作为附件添加到数据库中,并且在另外 2 个项目中运行良好,但由于某种原因现在无法运行。代码在这一行失败:
Dim rstRecord As Microsoft.Office.Interop.Access.Dao.Recordset = db.OpenRecordset( _
"SELECT * FROM [Projects] WHERE [Project ID]=" & FileX, _
Microsoft.Office.Interop.Access.Dao.RecordsetTypeEnum.dbOpenDynaset)
出现错误:
未处理的类型异常 'System.Runtime.InteropServices.COMException' 发生在 Alveare - 完整的管理工具.exe
附加信息:参数太少。预计 1。
在我传递参数时,有人知道为什么会这样吗?
谢谢
【问题讨论】:
-
FileX的值是否可能包含空格,这会导致 SQL 的执行出错? -
是否应该在 SQL 中引用
FileX的值?除非它是一个整数,否则它应该。我还注意到您必须拥有Option Strict Off,这绝不是好事。它允许各种问题潜入其中,否则可能会更早发现。 -
啊,在其他所有项目中,数据库的主键一直是一个ID整数,但是,在这个数据库中,它是一个字符串“F002 - X”。我需要改变什么来解决这个问题?