vb连接sql数据库的模块以及使用实例(详细)

来源:互联网 发布:遥感影像数据特点 编辑:程序博客网 时间:2024/06/14 15:52

打开VB6.0,新建工程SQL_data,新建一个EXE,并添加一个模块。如图

一:添加引用和部件(如下两图)蓝色的两个,是要选中打勾的。
注意,一个是“引用”,一个是“部件”。

              
二:添加一个模块 Data_Sql,并把图下面的复制粘贴到模块中。
               '连接SQL的模块

Public conn As ADODB.ConnectionPublic rs As ADODB.RecordsetPublic addFlag As Boolean      '声明部分Public Function OpenCn(ByVal Cip As String, ByVal users As String, ByVal pw As String) As Boolean '连接模块 填写数据库等信息Dim mag As StringOn Error GoTo strerrmagSet conn = New ADODB.Connectionconn.ConnectionTimeout = 25conn.Provider = "sqloledb"conn.Properties("data source").Value = Cip     '服务器的名字conn.Properties("initial catalog").Value = "pubs"          '库名'conn.Properties("integrated security").Value = "SSPI"      '登陆类型conn.Properties("user id").Value = users 'SQL库名conn.Properties("password").Value = pw '密码'sql = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;password=;Initial Catalog=pubs;Data Source=127.0.0.1"    '如果不用这个模块也行可以,这一句便是常用的引擎。'conn.ConnectionString = sql              conn.OpenOpenCn = TrueIf conn.State = 1 Then addFlag = TrueExit Functionstrerrmag:     mag = "Data can't connect"     Call MsgBox(mag, vbOKOnly, "Error:Data connect")     addFlag = False     Exit Function      '连接错误消息End Function'关闭数据库,释放连接Public Sub cloCn()On Error Resume NextIf conn.State <> adStateClosed Then conn.CloseSet conn = NothingEnd SubPublic Function openRs(ByVal strsql As String) As Boolean      '连接数据库记录集Dim mag As StringDim rpy As BooleanOn Error GoTo strerrmag     Set rs = New ADODB.Recordset     If addFlag = False Then rpy = True     With rs     .ActiveConnection = conn     .CursorLocation = adUseClient     .CursorType = adOpenKeyset     .LockType = adLockOptimistic     .Open strsql     End With     addFlag = True     openRs = True     'End        '将记录集给rs     Exit Functionstrerrmag:     mag = "data not connect"     Call MsgBox(mag, vbOKOnly, "error:connect")     openRs = False     End     'Exit Function '连接错误消息End FunctionPublic Sub cloRs()On Error Resume NextIf rs.State <> adStateClosed Then rs.CloneSet rs = Nothing '释放记录集End Sub

把它放入到模块文件中,以备调用。

三:下面两图是模块的代码图片和窗体的代码图片

       Private Sub Command1_Click()
a = Trim(Text1.Text)b = Trim(Text2.Text)c = Trim(Text3.Text)Call OpenCn(a, b, c)If addFlag = True Then MsgBox ("OK")Call openRs("select * from jobs")Set DataGrid1.DataSource = rs'rs.CloseEnd SubPrivate Sub Command2_Click()Unload MeEnd Sub

四:运行时的图片(下面两图)    到了这一步,一个简单的VB连接SQL的例子就完成了。
        

原创粉丝点击