VB6连接数据库

时间:2014-01-28 16:30:27

标签: vb6 connection-string visual-studio-6

好吧,我想做的事听起来很简单。我想加载一个表单并在表单加载调用一个sql语句,返回1项并将其放在TextBox1中。这是我到目前为止所做的。

 Private Sub Form_Load()

 Call openTheDatabase

 End Sub

 Public Function openTheDatabase() As Boolean

 '-- Here we want to open the database
 Dim sConnectionString As String
 Dim strSQLStmt As String

 '-- Build the connection string
 sConnectionString = "PROVIDER = MSDASQL;driver={SQL Server};database=databasename ;server=servername;uid=;pwd=;"


 strSQLStmt = "SELECT chvDealerName " & _
        "From dbo.tblDealers Where chrVSCAcctNum = '90442001'"

 TextBox1.Text = strSQLStmt

 End Function

修改

好吧是Text1.Text,但现在我只是在文本框中获取字符串,而不是实际的数据库条目

1 个答案:

答案 0 :(得分:6)

您可以在此处看到设置ADODB连接的一个可靠示例:http://www.timesheetsmts.com/adotutorial.htm

您的项目需要先引用ADODB库。要做到这一点:

  1. 打开您的项目
  2. 点击顶部的项目菜单,然后点击下拉列表中的参考
  3. 检查“Microsoft ActiveX数据对象2.x库”(x是您看到的最高编号 - 在我的Windows XP专业版SP2上,它是2.7“
  4. 项目示例:

    Private Sub Form_Load()
    
     Call openTheDatabase
    
     End Sub
    
     Public Function openTheDatabase() As Boolean
    
     '-- Here we want to open the database
     Dim sConnectionString As String
     Dim strSQLStmt As String
    
     '-- Build the connection string
     sConnectionString = "PROVIDER = MSDASQL;driver={SQL Server};database=databasename ;server=servername;uid=;pwd=;"
    
    
     strSQLStmt = "SELECT chvDealerName " & _
            "From dbo.tblDealers Where chrVSCAcctNum = '90442001'"
    
    'DB WORK
    Dim db As New ADODB.Connection
    Dim cmd As New ADODB.Command
    Dim rs As New ADODB.Recordset
    Dim result As String
    
    db.ConnectionString = sConnectionString 
    db.Open 'open connection
    
    With cmd
      .ActiveConnection = db
      .CommandText = strSQLStmt
      .CommandType = adCmdText
    End With
    
    With rs
      .CursorType = adOpenStatic
      .CursorLocation = adUseClient
      .LockType = adLockOptimistic
      .Open cmd
    End With
    
    If rs.EOF = False Then
        rs.MoveFirst
        Let result = rs.Fields(0)
    End If
    'close conns
    rs.Close
    db.Close
    Set db = Nothing
    Set cmd = Nothing
    Set rs = Nothing
    
    
    'set local box
    
    ' TextBox1.Text = strSQLStmt
    TextBox1.Text = result
    
    
     End Function