-3

有什么帮助吗?我的代码如下;

Imports System.IO
Imports System.Data
Imports System.Data.SqlClient 
Imports System.Data.OleDb

Partial Class Gallery
    Inherits System.Web.UI.Page

    Dim dbInsert As New OleDb.OleDbCommand
    Dim dbConnect As New OleDb.OleDbConnection
    Dim Line As String = Environment.NewLine
    Dim Message As String
    Dim dt As New DataTable()



    Protected Sub BtnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnUpload.Click

        Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & _
       Server.MapPath("App_Data\Web.accdb"))

        If FileUpload1.PostedFile IsNot Nothing Then
            Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
            Dim Picture As String = TxtPicturename.Text

            'Save files to disk
            FileUpload1.SaveAs(Server.MapPath("GalleryPics/" & FileName))

            Dim strQuery As String = "insert into Picture (FileName, FilePath)" _
             & " values(@FileName, @FilePath)"

            Dim cmd As New SqlCommand(strQuery)
            cmd.Parameters.AddWithValue("@FileName", FileName)
            cmd.Parameters.AddWithValue("@FilePath", "Gallery/" & FileName)
            cmd.CommandType = CommandType.Text

            Dim sql As String = "INSERT INTO Picture (PictureID, Picturename, CategoryNo) VALUES ('" & TxtPicturename.Text & "','" & FileUpload1.FileName & "');"
            dbInsert.CommandText = sql
            dbInsert.CommandType = CommandType.Text
            dbInsert.Connection = connection
            dbInsert.ExecuteNonQuery()
            MsgBox("Pictue successfully uploaded for " + Line + TxtPicturename.Text)

        End If

    End Sub
    Function checkFiletype(ByVal filename As String) As Boolean
        Dim ext As String = Path.GetExtension(filename)
        Select Case ext.ToLower()
            Case ".gif"
                Return True
            Case ".prg"
                Return True
            Case ".jpg"
                Return True
            Case "jpeg"
                Return True
            Case Else
                Return False
        End Select
    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load




    End Sub
End Class
4

1 回答 1

0

在尝试运行查询之前,您还没有打开与数据库的连接。

dbConnect.Open()在尝试使用您的查询之前放置。

IE

            dbConnect.Open() ''<------ HERE
            Dim cmd As New SqlCommand(strQuery)
            cmd.Parameters.AddWithValue("@FileName", FileName)
            cmd.Parameters.AddWithValue("@FilePath", "Gallery/" & FileName)
            cmd.CommandType = CommandType.Text

完成后不要忘记关闭它... IE

            dbInsert.ExecuteNonQuery()
            dbConnect.Close() '' <--------- HERE

更新

有关插入的一个很好的示例,请参阅本教程。 http://idealprogrammer.com/net-languages/code-samples/vbnet-aspnet-sql-command-insert-statement-source-code/

于 2012-12-05T19:29:36.847 回答