如何用VB访问数据库

2025-01-02 13:01:34
推荐回答(2个)
回答1:

以下我介绍一个比较简单的写法。首先须引用Projects-Components-Microsoft ADO Data Controls 6.0 (OLEDB).
之后在表单设置ADODC控件。然后输入以下代码:

方法1:
Private Sub cmdlogin_Click()
If txtuser = "" Then
MsgBox "Please fill in User Name.", vbInformation + vbOKOnly, "Information"
txtuser.SetFocus
Exit Sub
End If

If txtpassword = "" Then
MsgBox "Please fill in Password.", vbInformation + vbOKOnly, "Information"
txtpassword.SetFocus
Exit Sub
End If

Dim SQL As String
Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & App.Path & "\数据库名称.mdb"
Adodc1.CursorLocation = adUseClient
Adodc1.CommandType = adCmdText
SQL = "select * from 资料表名称 where UserName='" & Trim$(txtuser.Text) & "'And Password='" & Trim$(txtpassword.Text) & "'"
Adodc1.RecordSource = SQL
Adodc1.Refresh

If Adodc1.Recordset.RecordCount <> 0 Then
Unload Me
Form2.Show
Else
MsgBox "Invalid Username or password!", vbExclamation + vbOKOnly, "Error"
txtuser.SetFocus
End If
End Sub

----------------------------------

说明:
- Adodc1.ConnectionString主要是设置数据库连接。
- "Provider=Microsoft.Jet.OLEDB.4.0"为Access的Driver.
- Data Source=" & App.Path & "\数据库名称.mdb"为设置数据库的路径。若用App.Path的话数据库须和Vb程式放在同一个资料夹。Data Source也可以写成"Data Source=D:\数据库名称.mdb"

- SQL = "select * from 资料表名称 where UserName='" & Trim$(txtuser.Text) & "'And Password='" & Trim$(txtpassword.Text) & "'"为SQL语句简单的来说就是判断资料表内的UserName和 Password栏位是否等于txtuser.Text和
txtpassword.Text。若不是的话Adodc1.Recordset.RecordCount = 0 相反就Adodc1.Recordset.RecordCount <> 0 .

推介VB教学:http://hi.baidu.com/poi123p82/blog/item/9ac95ec95424fa1d7f3e6fd5.html
---------------------------------
方法2:

Private Sub cmdenter_Click()
If txtuser = "" Then
MsgBox "Please fill in User Name.", vbInformation + vbOKOnly, "Information"
txtuser.SetFocus
Exit Sub
End If

If txtpassword = "" Then
MsgBox "Please fill in Password.", vbInformation + vbOKOnly, "Information"
txtpassword.SetFocus
Exit Sub
End If

cn.ConnectionString = "provider=Microsoft.jet.OLEDB.4.0;" & _
"Persist security info= False; Data source=" & App.Path & "\Daily.mdb"
cn.Open

SQL = "select * from Login where UserName='" & Trim$(txtuser.Text) & "'" _
& "And Password='" & Trim$(txtpassword.Text) & "'"
rs.CursorLocation = adUseClient
rs.Open Trim$(SQL), cn, adOpenKeyset, adLockPessimistic

If rs.RecordCount = 0 Then
i = i + 1
If i < 3 Then
MsgBox "Invalid User Name or Password,Please re-type again.", vbExclamation + vbOKOnly, "Notice"
txtuser = ""
txtpassword = ""
txtuser.SetFocus
Else
MsgBox "Please contact your Administrator", vbExclamation + vbOKOnly, "Notice"
rs.Close
Unload Me
End If
Else
rs.Close
Unload Me
frmmain.Show
End If
End Sub

回答2:

data控件