求助,在做毕设,这部分不会,求程序。
在Text1中输入一个数值a,单击按钮,在Text2输出一个值。这个值是从Access数据表中查的,是第一列中数值大于a的第一个数。比如:a是6。数据表这一列有2、5、8、10。输出应为8.
程序代码:Option Explicit
Private Sub Command1_Click()
Dim i As Long
Dim rs As New ADODB.Recordset
Dim sql As String
i = Val(Text1.Text)
sql = "select top 1 * from zcsjb where 直径 > " & i & " ORDER BY 直径 ASC;" '生成 SQL 命令
rs.Open sql, Conn, adModeRead '以只读打开
If Not rs.EOF And Not rs.BOF Then '查询有结果
Text2.Text = rs.Fields("直径") '输出结果
Text3.Text = rs.Fields("宽度")
Else
Text2.Text = "无结果" '输出无结果
Text3.Text = "无结果"
End If
rs.Close '关闭表
Set rs = Nothing '释放内存
End Sub
Private Sub Form_Load()
'以下四行,我整个代码里没使用到,但你应该要使用到
Path = App.Path
If Right(Path, 1) <> "\" Then
Path = Path & "\"
End If
'打开数据连接
Call opendb
End Sub
Private Sub Form_Unload(Cancel As Integer)
'关闭数据连接
Call closedb
End Sub
程序代码:Option Explicit
Public Conn As New ADODB.Connection '数据库连接
Public Path As String
Public Sub opendb()
'连接数据库
If Conn.State = 1 Then '如果数据连接未关闭
Conn.Close '关闭它
DoEvents '确保已完成关闭操作
End If
Dim constr As String
Dim s As String
s = "D:\Documents\Documents\db2.mdb" '数据库路径
'因为测试时工程未保存,再加之数据库是临时,用完就删,所以写的绝对路径,你代码里应该像下面这样写相对位置。下面这行数据库在工程一起
's = Path & "db2.mdb"
If Dir(s) <> "" Then '数据库存在
constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & s & ";Persist Security Info=False"
Conn.Open constr
Else '否则报错退出
MsgBox "数据库不存在,程序无法运行!", vbCritical, "应用程序致命错误"
End
End If
End Sub
Public Sub closedb()
'关闭数据库连接
If Conn.State = 1 Then
Conn.Close '关闭数据连接
Set Conn = Nothing '释放内存
End If
End Sub
