使用 VB.NET 写入 MS-Access 数据库问题

Writing to MS-Access Database Issue using VB.NET

我正在使用 VB.Net 尝试写入我创建的数据库(需要写入数据库的机器是数据库的所有者,因此应该没有权限问题)。当我写入数据库的 subs 为 运行 时,我没有收到任何错误,但我的数据库中没有创建新记录。我已成功连接到数据库,因为我的返回记录工作正常。

写入数据库的Sub:

Public Sub LogThisCard(a As Object)
    Dim con As New OleDb.OleDbConnection
    Dim da As New OleDb.OleDbDataAdapter
    Dim sql As New OleDb.OleDbCommand
    Dim inMachine As String = "Yes"

    con.ConnectionString = Connection()
    con.Open()

    Try
        sql.Connection = con
        sql.CommandText = "INSERT INTO LogTable (MSA, Foo, Bar, Jack, Rabbit, Date_/_Time, Foxtrot) VALUES (@MSA, @Foo, @Bar, @Jack, @Rabbit, @DT, @Foxtrot)"

        sql.Parameters.AddWithValue("MSA", a.MSA)
        sql.Parameters.AddWithValue("Foo", a.Foo)
        sql.Parameters.AddWithValue("Bar", a.Bar)
        sql.Parameters.AddWithValue("Jack", a.Jack)
        sql.Parameters.AddWithValue("Rabbit", a.Rabbit)
        sql.Parameters.AddWithValue("DT", DateTime.Now())
        sql.Parameters.AddWithValue("Foxtrot", a.FoxTrot)

        da.InsertCommand = sql
        da.InsertCommand.ExecuteNonQuery()
    Catch ex As Exception
        Debug.Print(ex.ToString)
    End Try

    con.Close()
End Sub

数据库设计如下:

这可能是 Access 和您的 DateTime 参数的问题。如果 DateTime 允许空值,请更改您的插入以执行除 DateTime 之外的所有操作。如果插入有效,那么您就知道问题所在了。

我不确定为什么访问与 addwithvalue 有问题,但我经常看到它。我发现声明一个参数变量并设置属性然后在涉及日期时间时添加参数会更好。

示例:

Dim cmd As OleDb.OleDbCommand
Dim param As New OleDb.OleDbParameter
param.Direction = ParameterDirection.Input
param.DbType = DbType.Date
param.Value = Date.Now

cmd.Parameters.Add(param)