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:如果代码太长,影响可读性,可以用空格加"_"后,回车换行。
‘模块中的代码Public Function connectstr() As String
sqlpath = App.Path &"\数据库.mdb"
connectstr = "Provider=Microsoft.Jet.OLEDB.4.0Data Source=" &sqlpath &"" ‘access数据库
End Function
Public Function runselect(ByVal sqlm As String) As ADODB.Recordset '返回记录集
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
On Error GoTo run_error
Set cn = New ADODB.Connection
cn.Open connectstr()
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.LockType = adLockOptimistic
rs.Open Trim(sqlm), cn, adOpenDynamic
Set runselect = rs
Set rs = Nothing
Set cn = Nothing
run_error:
MsgBox Err.Description
End Function
’窗体中的代码.................
Private Sub Combo1_Change()
Dim mrc As New ADODB.Recordset
Set mrc = runselect("select * from 表 where 字段='" &Trim(Combo1.Text) &"'")
Set DataGrid1.DataSource = mrc '显示在 datagrid 中
End Sub
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)