當前位置:編程學習大全網 - 編程語言 - VB小白(0基礎)如何用VB編程連接SQL並且對其進行操作

VB小白(0基礎)如何用VB編程連接SQL並且對其進行操作

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控件,方便!

  • 上一篇:請大家幫幫忙,以“科技奧運”為主題,就某個方面的壹個具體問題,提出自己的建議和創意。(急用)
  • 下一篇:Video4Linux的簡介
  • copyright 2024編程學習大全網