VB.NET Access DB INSERT Not Inserting Data?

馋奶兔 提交于 2019-12-24 18:15:09

问题


I'm trying to insert a row into a table I have in Access. The table is named Site and it has two columns, SiteId (AutoNumber) and SiteName (Text). For testing purposes, I grabbed a value from an Excel sheet and attempted to insert the value into the SiteName column with the following code...

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim App As New Excel.Application
    Dim WB As Excel.Workbook = App.Workbooks.Open("C:\MyFile.xlsx")
    Dim WS As Excel.Worksheet = DirectCast(WB.Worksheets(2), Excel.Worksheet)
    App.Visible = False

    Dim Range As Excel.Range
    Range = WS.Range("A8")
    Dim cnn As New OleDbConnection(My.Settings.cnn)
    Dim cmd As New OleDbCommand("INSERT INTO Site(SiteName) VALUES(@SiteName)", cnn)
    cmd.Parameters.Add("@SiteName", OleDbType.Char).Value = Range.Value.ToString

    Try
        Using cmd.Connection
            cmd.Connection.Open()
            cmd.ExecuteNonQuery()
        End Using
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

Even if I remove the cmd.Parameters line and just put a straight value like Values('Test') it doesn't make an insert. I get no errors in the code as I perform the command. Why is the value not working? I have verified the data returning from the Excel sheet and that works fine. I just can't get it to insert into the table in Access. The connection works fine as well because if I use this Insert...

Dim cmd As New OleDbCommand("INSERT INTO Site VALUES(@SiteName)", cnn)

it will tell me that the number of query values does not match the field count or something of the sort.


回答1:


The value IS inserted (at least most of the times) ;) Have you ever checked the content of the mdb (in the output folder!) manually?

You have added the mdb file to your project? Go to the properties window of the file and set "Copy to output directory" to "NEVER".

NORMALLY when you add the file, it is set to "copy if newer" or "copy always". That means whenever you run your app in the debugger the mbd file from the project directory is copied to the debug/release folder and OVERWRITES any file that is already inside (and where you have stored your records).



来源:https://stackoverflow.com/questions/13515419/vb-net-access-db-insert-not-inserting-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!