无法从Access数据库查询中检索数据到我的VB程序

时间:2016-07-13 21:43:50

标签: sql vb.net access-vba

所以这是我目前的代码...... 我有2个DateTimePickers,其中用户选择一周的第一天和一周的最后一天,一旦选择这两个我想计算每天工作的小时数并添加它们以便我可以显示工作小时数选择的天数间隔。

我的工作表包含一个idEmployee,Date,ArrivalTime,DepartureTime和一个计算列(Hrs_worked),显示当天工作的小时数。

当我运行程序时,会弹出一个消息框,显示“从类型'DBNull'转换为'String'类型无效”或“条件表达式中的数据不匹配” 我是否需要将datetimepickers值更改为字符串值?

我在使用Access数据库的Visual Basic Express 2010上工作

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

    Dim provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    Dim dataFile As String = "E:\SIDB.accdb"
    Dim connString As String = provider & dataFile
    Dim myConnection As OleDbConnection
    Dim cmd As OleDbCommand

    Dim qHrsWorked As String = "SELECT SUM(Hrs_worked) FROM Work WHERE IdEmployee = " & idEmptxt.Text & " AND Date >= " & firstDayDTP.Value & " AND Date <= " & lastDayDTP.Value & ""

    myConnection = New OleDbConnection(connString)
    Try
        myConnection.Open()
        cmd = New OleDbCommand(qHrsWorked, myConnection)
        Dim reader As OleDbDataReader = cmd.ExecuteReader()

        While reader.Read
            hrsWorkedtxt.Text = reader.Item(0)

        End While
        reader.Close()
        cmd.Dispose()
        myConnection.Close()

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try


End Sub

3 个答案:

答案 0 :(得分:1)

我几年没有编写Access查询,现在没有尝试,但如果我没记错,查询中的DateTime值需要用哈希标记(#)包围。

Dim qHrsWorked As String = _
    "SELECT SUM(Hrs_worked) FROM Work WHERE IdEmployee = " & idEmptxt.Text & _
    " AND Date >= #" & firstDayDTP.Value & "# AND Date <= #" & LastDayDTP.Value & "#"

答案 1 :(得分:0)

我怀疑这是因为您使用Textbox.Text作为日期选择器。您只能在控件具有焦点时使用该属性。尝试用.Value替换那些?

答案 2 :(得分:0)

在SQL中,您必须使用格式化的字符串表达式来表示日期值:

@Test
public void testDelete() throws SQLException {
    // Given
    String dateStr = "09-May-2016";
    String word = "testWord";
    PreparedStatement insertemp = conn
                .prepareStatement("insert into " + tableName + "(PUBLISHDATE,WORD,FREQUENCY) values(?,?,?)");
        insertemp.setString(1, dateStr);
        insertemp.setString(2, word);
        insertemp.setInt(3, frequency);
        insertemp.executeUpdate();

    // When
    assertEquals(2, derbyDb.contain(dateStr, word));
    derbyDb.delete();

    // then
    assertEquals(0, derbyDb.contain(dateStr, word));
}