1、打开代码窗口,添加引用:Imports System.Data.SqlClient。
2、输入以下代码:
“Public conn1 As SqlConnection = New SqlConnection _
("server=192.168.1.79Initial Catalog= studentUser ID= panqePWD=shentai768@")”,vb就已经成功连接sql数据库了。
3、代码详解:声明关键字Public(因为是全局变量,所以用Public 来声明)。
4、连接参数。
5、如果SQL 数据库就在本机,则用以下代码连接:
("server=.Integrated Security=FalseInitial Catalog= studentUser ID= panqePWD=shentai768@")。
6:如果代码太长,影响可读性,可以用空格加"_"后,回车换行。
Private Sub Form_Load() '此段代码的主要作用是当窗体打开时就连接数据库
Dim conn As New ADODB.Connection
Dim connectionstring As String
connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0Data Source=" & App.Path & "\DATE.mdbPersist Security Info=False" '数据库路径
conn.Open connectionstring
End Sub
Private Sub Command1_Click()
Static n As Integer
If n >= 3 Then
MsgBox "输入密码次数大于3次,不允许继续登陆"
End
End If
Set conn = New ADODB.Connection
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0Persist Security Info=FalseData Source=DATE.mdbJet OLEDB:Database Password="
Dim sql As String
Dim rs_login As New ADODB.Recordset
If Trim(Text1.Text) = "" Then '检测用户名正确与否
MsgBox "用户名不能为空,请重新输入!", vbOKOnly + vbExclamation, "错误"
Text1.SetFocus
Else
sql = "select * from 验证 WHERE 用户名='" & Trim(Text1.Text) & "'"
rs_login.Open sql, conn, adOpenKeyset, adLockPessimistic
If rs_login.EOF = True Then
MsgBox "用户名不存在,请重新输入!", vbOKOnly + vbExclamation, "错误"
Text1 = ""
Text1.SetFocus
Else '检测密码正确与否
If Trim(rs_login.Fields(2)) = Trim(Text2) Then
rs_login.Close
Unload Me
Form2.Show
Else
n = n + 1
MsgBox "第" & n & "次密码错误,请重新输入!", vbOKOnly + vbExclamation, "错误"
Text2.SetFocus
End If
End If
End If
End Sub
Private Sub Command2_Click()
MsgBox "您已成功退出!", vbOKOnly + vbExclamation, "提示"
Unload Me
End Sub
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)