Sql语句返回不正确的数据

时间:2013-12-22 19:44:51

标签: vb.net visual-studio-2010 visual-studio ms-access

我很困惑为什么我的SQL select语句返回不正确的数据。在我的数据库中,值为009698,它返回9698。有人可以解释为什么会发生这种情况。

它是MS Access 2010数据库,列为text,大小为6.

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    Try
        DBConnection.connect()

        sql = "SELECT MAX([Request no]) from Requests WHERE Customer = '" & cmbCustomer.Text & "' "
        Dim cmd As New OleDb.OleDbCommand
        Dim id As Integer

        cmd.CommandText = sql
        cmd.Connection = oledbCnn
        dr = cmd.ExecuteReader

        While dr.Read()
                id = CInt(dr.Item(0))
                id = (id) + 1
        End While

        'MessageBox.Show("00" & id)
        'sql = "INSERT INTO Requests ([Request no], Customer) VALUES ('" & id & "', '" & cmbCustomer.Text & "')"

        cmd.Dispose()
        'dr.Close()
        oledbCnn.Close()

    Catch ex As Exception

        MessageBox.Show(ex.Message)

    End Try
End Sub

2 个答案:

答案 0 :(得分:3)

您将返回的值视为整数,因此'009698'和'9698'在此上下文中的值相同。

如果您想稍后将其转换为六位数字符串,则可以执行以下操作:

Dim stringId as String
While dr.Read()
    id = CInt(dr.Item(0))
    id = (id) + 1
    stringId = id.ToString().PadLeft(6, "0"c)
End While

答案 1 :(得分:1)

由于字段是文字,为什么不使用GetString上的DataReader功能。

Dim id As String

While dr.Read
  ''The string value returned from the database
  Dim stringID = dr.GetString(0)

  ''convert the string to an int and add 1
  Dim numericID = CInt(stringID) + 1

  ''convert the number back to a string with leading 0
  id = numericID.ToString.PadLeft(stringID.Length, "0")

End While

我假设您正在尝试从数据库获取字符串值,将其转换为数字,添加一个,然后将其转换回带有前导零的字符串格式。