我的程序无法自动计算我的ID。我缺少一些东西。有人可以帮我看看
Private Sub getNextNumber()
If Not app.State = ConnectionState.Open Then
'open connection
app.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("select top 1 ID from ADMIN order by ID desc;", app)
Dim dt As New DataTable
'fill data to datatable
da.Fill(dt)
app.Close()
If dt.Rows.Count > 0 Then
txtID.Text = (Val(dt.Rows(0)(0)) + 1).ToString.PadLeft(10, "B")
Else
txtID.Text = "1".PadLeft(10, "B")
End If
End Sub
Private Function getLastNumber() As Integer
Dim app1 As New OleDb.OleDbConnection
app1.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=MYX.accdb"
If Not app1.State = ConnectionState.Open Then
app1.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("select top 1 ID from ADMIN order by ID desc;", app1)
'desc = sort the data returned in descending order
Dim dt As New DataTable
da.Fill(dt)
app1.Close()
If dt.Rows.Count > 0 Then
Return Val(dt.Rows(0)(0))
End If
Return 0
End Function
我在这一部分是否编码错误?
If dt.Rows.Count > 0 Then
txtID.Text = (Val(dt.Rows(0)(0)) + 1).ToString.PadLeft(10, "B")
Else
txtID.Text = "1".PadLeft(10, "B")
End If
答案 0 :(得分:0)
Using...End Using
块将关闭并处置您的数据库对象,即使发生错误也是如此。在本地创建连接时,无需检查连接状态。
将连接字符串直接传递给连接的构造函数。同样,将sql语句和连接直接传递给命令的构造函数。您不需要DataAdapter
或DataTable
。
.ExecuteScalar
返回一个对象(结果集的第一行,第一列),因此我们在Using块外声明一个Object变量,以便在关闭连接后可以使用它。我们可以使用.ExecuteScalar
,因为您只返回1行,而该行仅返回一列。
接下来,在正确关闭并处置连接和命令后,我们检查retVal
是否为Nothing
,如果为Private conString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=MYX.accdb"
Private Function getLastNumber() As Integer
Dim retVal As Object
Using app1 As New OleDb.OleDbConnection(conString)
Using cmd As New OleDbCommand("select top 1 ID from ADMIN order by ID desc;", app1)
app1.Open()
retVal = cmd.ExecuteScalar()
End Using
End Using
If retVal Is Nothing Then
Return 0
End If
Dim arrChar = retVal.ToString.ToCharArray()
Dim result = (From c In arrChar
Where Char.IsNumber(c)
Select c).ToArray
Dim num = CInt(String.Join("", result))
Return num
End Function
,则返回0。
如果未通过测试,则更改为Char数组。使用Linq提取数组的数字。最后,将其连接为一个字符串并转换为数字。
Private Sub GetNextID()
Dim retVal As Object
Using app As New OleDbConnection(conString)
Using cmd As New OleDbCommand("select top 1 ID from ADMIN order by ID desc;", app)
app.Open()
retVal = cmd.ExecuteScalar
End Using
End Using
If retVal Is Nothing Then
txtID.Text = "1".PadLeft(10, "B"c)
Return
End If
Dim arrChar As Char() = retVal.ToString.ToCharArray
Dim result = (From c In arrChar
Where Char.IsNumber(c)
Select c).ToArray
Dim num = CInt(String.Join("", result))
txtID.Text = (num + 1).ToString.PadLeft(10, "B"c)
End Sub
明智的选择您的下属...
{{1}}
我希望这是单个用户,否则这些方法会遇到很大的问题。