2016-04-07 79 views
1

我有一個問題從表中獲取最後id的值。在哪裏加載SELECT MAX(id)在vbnet

由於加載整列會給我一個未來的問題(DataTable有其限制),所以我決定尋找另一種解決方案,但我沒有運氣讓它工作。

我有字符串命令,但我不知道在哪裏存儲返回的值。 這裏是我的代碼:

 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插入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

回答

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 
+0

錯誤類型'DAO.Recordset'未定義。 \t錯誤'CurrentDB'未被聲明。由於其保護級別,它可能無法訪問。 \t「我試圖通過添加'Microsoft ActiveX Data Objects 2.x Library'修復錯誤,但沒有解決第二個錯誤。」我會添加我的refences也許它會幫助 – pwalaako2

+0

好像我需要先學習adodb可以充分利用功能...我現在投票:) – pwalaako2