我在从表中获取最后id
的值时遇到问题。
由于加载整个列会在将来给我一个问题(DataTable
有其限制)所以我决定寻找另一个解决方案,但我没有运气让它工作。< / p>
我有字符串命令,但我不知道存储返回值的位置。 这是我的代码:
Dim query As String = "SELECT MAX(id) AS LastId FROM Table1"
Dim dtmain As New DataTable
Try
With sqlcmd
.CommandText = query
.Connection = sqlcon
End With
With sqladp
.SelectCommand = sqlcmd
.Fill(dtMain)
End With
MsgBox("last id = " & dtmain.Rows(0)("LastId"))
Catch ex As Exception
End Try
我什么都没得到,而msgbox
甚至没有表现出来。
注意:我希望表中的最后一个id
和 NOT 插入的id
。
这是我的参考和声明:
Imports System.Data.OleDb
Private conn As OleDbConnection
Private adapter As OleDbDataAdapter
Private cmdd As OleDbCommand
我还在项目参考
中添加了Microsoft ADO Ext 2.8 for DDL and Security
答案 0 :(得分:1)
如果您的数据来源位于当前数据库中:
Dim dbConnect As Database
Dim rstRecordset As DAO.Recordset
Set dbConnect = Access.CurrentDb
Dim query As String = "SELECT MAX(id) AS LastId FROM Table1"
Set rstRecordset = dbConnect .OpenRecordset(query)
MsgBox("last id = " & rstRecordset.Fields(0).value & ""))
dbConnect.Close
Set dbConnect = Nothing
Set rstRecordset = Nothing
如果您的数据来源位于另一个Access数据库中:
Dim cnnConn As ADODB.connection
Dim rstRecordset As ADODB.Recordset
Dim cmdCommand As ADODB.Command
' Open the connection.
Set cnnConn = New ADODB.connection
With cnnConn
.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0"
.Properties("Jet OLEDB:Database Password") = "pass"
.Open "D:\Databases\Database.mdb"
End With
' Set the command text.
Set cmdCommand = New ADODB.Command
Set cmdCommand.ActiveConnection = cnnConn
With cmdCommand
.CommandText = "SELECT MAX(id) AS LastId FROM Table1"
.CommandType = adCmdText
.Execute
End With
' Open the recordset.
Set rstRecordset = New ADODB.Recordset
Set rstRecordset.ActiveConnection = cnnConn
rstRecordset.Open cmdCommand
MsgBox("last id = " & rstRecordset.Fields(0).value & ""))
' Close the connections and clean up.
cnnConn.Close
Set cmdCommand = Nothing
Set rstRecordset = Nothing
Set cnnConn = Nothing