vb连接数据库

最近实习公司要求用vb+MapX做一个模拟实时追踪的系统。由于以前没有接触过vb和MapX所以感觉时间花了不少效果却不是很明显
一个vb连接数据库就弄了好久,把代码贴出来分享一下

1、在工程里引入 Microsoft ActiveX Data Objects 2.X libary;
              Microsoft DAO 3.51 Object Libary
或者直接添加timer控件再删除
2、定义conn,rs
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
3、分两种情况
      
        'a有数据源情况(数据源名:vbSQLserver)
         Set conn = New ADODB.Connection
        Set rs = New ADODB.Recordset
       
        conn.ConnectionString = "DSN=vbSQLserver;uid=sa;pwd=master;"
        conn.ConnectionTimeout = 30
        conn.Open
       rs.Open "select * from user_info", conn, adOpenStatic, adLockReadOnly, adCmdText
        Dim i As String
        For t = 0 To Val(rs.RecordCount) - 1
            i = Trim(rs.Fields("user_name").Value)
        rs.MoveNext
        Print (i)
        Next t
      
       Set rs = Nothing
        Set conn = Nothing
      
       'b无数据源情况
        Set conn = New ADODB.Connection
        Set rs = New ADODB.Recordset
        conn.ConnectionString = "Driver={sql server};server=192.168.1.200;uid=sa;pwd=master;database=user_data"
        conn.ConnectionTimeout = 10000000
        conn.Open
        rs.Open "select user_name from user_info", conn, adOpenStatic, adLockReadOnly, adCmdText
        Dim i As String
            Print (Val(rs.RecordCount) - 1)
            For t = 0 To Val(rs.RecordCount) - 1
              i = Trim(rs.Fields("user_name").Value)
              Print (i)
              rs.MoveNext
            Next t
            
    End Sub

     Set rs = Nothing
     Set conn = Nothing


你可能感兴趣的:(DAO,sql,SQL Server,Microsoft,vb)