插入Access返回错误

时间:2014-03-31 15:40:08

标签: vb.net ms-access-2010

我尝试将2个datetimepicker插入到我的数据库中但是@ p1中的错误表示对象引用未设置为对象的实例 我的代码是:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click


                Dim date1 As Date = DateTimePicker1.Value.ToShortDateString()
                Dim date2 As Date = DateTimePicker2.Value.ToShortDateString()
                oleConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\c2cdb.accdb")
                Dim cb As String = "insert into Reqmain(DateOfResive,DateOfIssue,UnitID,DeviseType,expectedCrush,Attachments,WorkerID) VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7)"
                cmd.Parameters.AddWithValue("@p1", date1)
                cmd.Parameters.AddWithValue("@p2", date2)
                cmd.Parameters.AddWithValue("@p3",convert.ToInt32(ComUnits.ValueMember))
                cmd.Parameters.AddWithValue("@p4", tbDeviseType.Text)
                cmd.Parameters.AddWithValue("@p5", tbExpCrush.Text)
                cmd.Parameters.AddWithValue("@p6", tbattach.Text)
                md.Parameters.AddWithValue("@p7",convert.ToInt32(comWorker.ValueMember))
                cmd = New OleDbCommand(cb)
                cmd.Connection = oleConn
                oleConn.Open()
                cmd.ExecuteNonQuery()
                oleConn.Close()
          End Sub

1 个答案:

答案 0 :(得分:1)

这个小代码对我有用:

Try
        Dim con As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=yourDB.accdb;")
        Dim cb As String = "insert into Table1 (Date1, Sample1) VALUES (@p1, @p2)"
        Dim cmd As New System.Data.OleDb.OleDbCommand
        cmd.Connection = con
        cmd.CommandText = cb
        cmd.Parameters.AddWithValue("@p1", Me.DateTimePicker1.Value.ToShortDateString())
        cmd.Parameters.AddWithValue("@p2", Me.TextBox1.Text)
        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
Catch ex As Exception
        MessageBox.Show(Err.Description)
End Try