怎么实现VB和SQL Server连接啊?

2024-12-01 14:55:59
推荐回答(3个)
回答1:

Dim conn As New ADODB.Connection, rs As New ADODB.Recordset

Private Sub Form_Load()

conn.ConnectionString = "Driver={SQL Server};SERVER=ALLEN;DATABASE=你数据库的名字;UID=sa;PWD="
conn.Open()

End Sub

===============================
以上的是连接的代码

连接以后,每次运用都要先open,记得用完以后要close
代码如下:
conn.Open("Provider=SQLOLEDB;Data Source=ALLEN;UID=sa;PWD=")
下面就是你的SQL语句,如:sql="select * from test"
最后就是要关闭:conn.close()

回答2:

连接数据库简单的登录 代码如下
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim loginflag As Boolean

Private Sub Command1_Click()
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
'建立无源数据库连接
conn.ConnectionString = "driver={sql server};server=12-3FDA18CE0DDC;uid=sa;pwd=sa;Database=test"
conn.ConnectionTimeout = 50
conn.Open
Dim str As String
'连接连接对象
Set rs.ActiveConnection = conn
'设置游标类型
rs.CursorType = adOpenDynamic
If Trim(Text1.Text = "") Then
MsgBox "用户名不能为空,请重新输入用户名!", vbOKOnly + vbExclamation, "警告"
Text1.SetFocus
Else
'设置查询字符串
str = "select * from tt where name ='" & Trim(Text1.Text) & "'"
rs.Open str
If rs.EOF = True Then
MsgBox "没有这个用户,请重新输入用户名!", vbOKOnly + vbExclamation, "警告"
Text1.SetFocus
Else
'登录成功,连接主窗口
If (Trim(Text2.Text) = Trim(rs.Fields("password"))) Then
loginflag = True
Me.Hide
Form2.Show
MsgBox "登陆成功"
Else
MsgBox "密码不正确,请重输入密码!", , "警告"
Text2.SetFocus
SendKeys "{Home}+{End}"
End If
End If
End If
End Sub

Private Sub Command2_Click()
Me.Hide
loginflag = False
End
End Sub

回答3:

和SQL数据库连接可以吗,