【问题标题】:Sql statement returning incorrect datasql语句返回不正确的数据
【发布时间】:2013-12-22 19:44:50
【问题描述】:

我对为什么我的 SQL 选择语句返回不正确的数据感到困惑。在我的数据库中,值为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

【问题讨论】:

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


    【解决方案1】:

    您将返回值视为整数,因此“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
    

    【讨论】:

    • Szymon 我该如何修改
    • 我想要做的是得到 '009698' 的实际值,而不是 9698。顺便说一句,您的代码在 6 处产生 'expression expected'。谢谢
    • 对不起,我给你的是 C# 语法,而不是 VB.NET。使用这个:id.ToString().PadLeft(6, "0"c)
    • 错误:对象引用未设置为对象的实例。谢谢
    【解决方案2】:

    既然字段是文本,为什么不在DataReader上使用GetString函数。

    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
    

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

    【讨论】:

    • 该字段是“文本”字段,我不希望将其转换为 int,只保留为字符串。谢谢
    猜你喜欢
    • 2016-12-06
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    相关资源
    最近更新 更多