zhangrong 发表于 2014-7-9 09:13:20

VB如何连接SQL数据库并登录?

VB如何连接SQL数据库并登录?

ytn2001 发表于 2014-7-9 09:14:28

Option Explicit
Private Function Selectsql(SQL As String) As ADODB.Recordset       '返回ADODB.Recordset对象
   Dim ConnStr As String
    Dim Conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Set rs = New ADODB.Recordset
    Set Conn = New ADODB.Connection
   
    'On Error GoTo MyErr:
    ConnStr = "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=登录数据库用户名(默认为sa);Password=登录数据库密码;Initial Catalog=数据库名;Data Source=服务器名(默认为:MERRYCHINA)"      '这是连接SQL数据库的语句   
Conn.Open ConnStr
    rs.CursorLocation = adUseClient
    rs.Open Trim$(SQL), Conn, adOpenDynamic, adLockOptimistic
    Set Selectsql = rs
    'Exit Function
'MyErr:
    'Set rs = Nothing
    'Set Conn = Nothing '释放相关的系统资源
    'MsgBox Err.Description, vbInformation, "系统提示" '显示出错信息
End Function
Private Sub Form_Load()
    Dim SQL As String
    Dim rs As ADODB.Recordset
    Dim X As Long
    On Error GoTo Err_box
    SQL = " select * from 用户表"
    Set rs = Selectsql(SQL)
    If rs.RecordCount > 0 Then
      rs.MoveFirst
      For X = 1 To rs.RecordCount
            Combo1.AddItem rs.Fields("用户名").Value
            rs.MoveNext
      Next X
      Combo1.ListIndex = 0
    End If
    rs.Close
    Exit Sub
Err_box:
   End Sub
Private Sub Command1_Click()
    Dim SQL As String
    Dim rs As ADODB.Recordset
    If Text1.Text = "" Then
       MsgBox "请输入口令!", 16
      Text1.SetFocus
      Exit Sub
    End If
    If Combo1.Text = "" Then
         MsgBox "请选择登录用户!", 16
      Combo1.SetFocus
      Exit Sub
    End If
    SQL = "SELECT * FROM 用户表 WHERE 用户名='" & Combo1.Text & "' AND 密码='" & Text1.Text & "' "
    Set rs = Selectsql(SQL)
    If rs.RecordCount > 0 Then
      Form1.Show   '想要打开的主窗体
      MsgBox "恭喜兄弟,登录成功!", 64, "提示"
      Unload Me
    Else
      MsgBox "口令不对,请重新输入!", 16, "提示"
      Text1.SetFocus
    End If
End Sub
'**********************************************************************
'说明:1) 在工程中引用Microsoft ActiveX Data Objects 2.8 Library ,其它版本也行如:2.0
'   2) 在窗体中加Texe1.text(文本框控件),Combo1.text(组合框控件),Command1(命令按钮)各一个
'   3) 在SQL Server2000中创建数据库,新建表"用户表",表中包含"ID,姓名,密码"等字段,然后将以上代码复制,OK搞定
   4) 以上方式无需加载ADO控件,方便!
页: [1]
查看完整版本: VB如何连接SQL数据库并登录?