Setup An Odbc Connection Automatically
Const ODBC_ADD_DSN = 1        ' Add data source
Const ODBC_CONFIG_DSN = 2    ' Configure (edit) data source
Const ODBC_REMOVE_DSN = 3    ' Remove data source
Const vbAPINull  = 0&
Declare Function SQLAllocEnv Lib "odbc32.dll" (phenv&) As Integer
Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" (Byval hwndParent As Long, Byval fRequest As Long, Byval lpszDriver As String, Byval lpszAttributes As String) As Long

Public Function CreateSQLDSN(Byval DSN As String, Byval Server As String, Byval Database As String, _
Byval Driver As String, Byval Description As String) As Boolean
 Dim strAttributes As String
 SQLConfigDataSource vbAPINull, ODBC_REMOVE_DSN, Driver, "DSN=" & DSN
 strAttributes = "DSN=" & DSN & Chr$(0) & _
 "Description=" & Description & Chr$(0) & _
 "Server=" & Server & Chr$(0) & _
 "Database=" & Database & Chr$(0)
 If SQLConfigDataSource(vbAPINull, ODBC_ADD_DSN, Driver, strAttributes) = 0 Then
  CreateSQLDSN = False
 Else
  CreateSQLDSN = True
 End If
End Function

 Dim conn As New ODBCConnection
 Dim tqry As New ODBCQuery
 Dim trst As New ODBCResultSet
 Dim ProdCode As String
 Dim js As Long 
 Dim msg As String
 
 If Not conn.ConnectTo("ERP2002","hjj","sss") Then
  Msgbox "Could not connect to ERP2002!",46,"Error"
  Exit Sub
 Else
  Msgbox  "OK!"&conn.GetLsdoMasterRevision ,48,"Successed"
  Set tqry.Connection=conn
  Set trst.Query=tqry
  tqry.SQL="SELECT TOP 10 進出存.生號, 進出存.進數之總計 FROM 進出存 ORDER BY 進出存.進數之總計 DESC;"
  trst.Execute
  If trst.IsResultSetAvailable Then
   Do
    trst.NextRow
    prodcode=trst.GetValue("生號",ProdCode)
    js=trst.GetValue("進數之總計",js)
    msg=msg & Chr(13) & prodcode & " -->" & js
   Loop Until trst.IsEndOfData
   Msgbox msg,,"Prod states"
   trst.Close(db_Close)
  Else
   Msgbox "cannot run the sql query",48
  End If
  conn.Disconnect
 End If

posted on 2005-07-07 08:56  James Wong   阅读(675)  评论(0)    收藏  举报