2024年4月11日发(作者:)
VB连接数据库的方法大全
1、 Adodc连接法
(1) 非编程连接法:操作方便,但会因数据移动造成数据库断链接。
(2) 编程连接法:解决了数据移动造成数据库断链接的现象,使用的语句如下:
①路径不需要获取的情况:
tionString = "Provider=.4.0;Data Source=" + + ";Persist Security Info=False" '
设置数据库路径
dType = adCmdText '设置记录源
Source = "select * from message" '连接数据库的message表文件
附:dType的说明
dType = 8 :adcmdunkown
产生Recordsource命令类型未知,通常使用SQL
dType = 1 :adcmdtext
Recordsource由命令文本产生,通常使用SQL
dType = 2 :adcmdtable
Recordsource由为单个表名
dType = 4 :adcmdstoredproc
Recordsource由存储过程产生
连接SQL Server 的代码:
Private Sub Form_Load()
tionString = "Provider=SQLOLEDB.1;Password=123;Persist Security Info=True;User ID=sa;Initial Catalog=仓库;Data
Source=FNL-XQURVVITG0W"
dType = adCmdText '设置记录源
Source = "select * from 库存表" '连接数据库“仓库”的“库存表”文件
h
End Sub
②数据库名和表名可通过文本框方式获取:首先新建两个文本框,取名为txtpath 和 txttbl,在命令按钮的click事件中添加下面代码:
Dim path As String, tabel As String
path = "" & & ".mdb"
tabel =
tionString = "Provider=.4.0;Data Source=" & & path & ";Persist Security Info=False" '
设置数据库路径
dType = adCmdText '设置记录源
Source = "select * from " & tabel '连接数据库的message表文件
附:文本框连接Adodc的方法:
Set urce = Adodc1
eld = "姓名"
附:常用数据库操作命令按钮代码
添加记录按钮代码:
Private Sub Command1_Click()
'添加新纪录
End Sub
提交按钮代码:
Private Sub Command2_Click()
'如果是文本框修改数据库信息,就必须使用If句式判断主索引是否为空
'保存
h '刷新
End Sub
首记录按钮代码:
Private Sub Command3_Click()
If Count = 0 Then
MsgBox "没有记录,不能跳转", , "系统提示"
Else
rst
End If
End Sub
末记录按钮代码:
Private Sub Command4_Click()
If Count = 0 Then
MsgBox "没有记录,不能跳转", , "系统提示"
Else
st
End If
End Sub
上一条记录按钮代码:
If Count = 0 Then
MsgBox "没有记录,不能跳转", , "系统提示"
ElseIf Count = 1 Then
rst
Else
evious
If Then
rst
MsgBox "已到第一条记录,不能再跳转", , "系统提示"
End If
End If
End Sub
下一条记录代码:
If Count = 0 Then
MsgBox "没有记录,不能跳转", , "系统提示"
ElseIf Count = 1 Then
st
Else
xt
If Then
st
MsgBox "已到最后一条记录,不能再跳转", , "系统提示"
End If
End If
End Sub
删除记录代码:
If Count = 0 Then
MsgBox "没有记录可供删除", , "系统提示"
ElseIf Count = 1 Then
MsgBox "你已删除最后一条记录了", , "系统提示"
Else
xt
If Then
st
End If
End If
End Sub


发布评论